SetToLoki Posted June 25, 2009 Share Posted June 25, 2009 hi I am creating a new class and I want to use my previously connected mysql class inside of it, being able to reference the mysql inside the new class I am creating. example of what I tried to do <?php class user { private $user = ""; private $userlevel = ""; private $db; public function _construct() { global $db_host, $db_user, $db_pass, $db_name; $this->db = new MySQL($db_host, $db_user, $db_pass, $db_name); } function test() { $sql = "SOME SQL CODE"; $results = $this->db->query($sql); $rows = $this->db->fetch_assoc($results); } } ?> Link to comment https://forums.phpfreaks.com/topic/163629-solved-class-within-a-class/ Share on other sites More sharing options...
gevans Posted June 25, 2009 Share Posted June 25, 2009 Hey, global $db_host, $db_user, $db_pass, $db_name; Instead of setting the variables as global, you should pass them, in this case, via the constructor for use with the MySQL class. You didn't state if there was a problem. Link to comment https://forums.phpfreaks.com/topic/163629-solved-class-within-a-class/#findComment-863351 Share on other sites More sharing options...
SetToLoki Posted June 25, 2009 Author Share Posted June 25, 2009 sorry my error was Fatal error: Call to a member function query() on a non-object when I tried to do it my way, yeah I probably shouldn't do it as globals is an old habit I need to break Link to comment https://forums.phpfreaks.com/topic/163629-solved-class-within-a-class/#findComment-863353 Share on other sites More sharing options...
gevans Posted June 25, 2009 Share Posted June 25, 2009 Does your MySQL have any error checking? What if it fails? Perhaps it's not instantiating. Link to comment https://forums.phpfreaks.com/topic/163629-solved-class-within-a-class/#findComment-863356 Share on other sites More sharing options...
gevans Posted June 25, 2009 Share Posted June 25, 2009 Actually, just saw it, _construct() For the constructor to run automatically on instantiation you require two underscores; __construct() Link to comment https://forums.phpfreaks.com/topic/163629-solved-class-within-a-class/#findComment-863360 Share on other sites More sharing options...
SetToLoki Posted June 25, 2009 Author Share Posted June 25, 2009 Actually, just saw it, _construct() For the constructor to run automatically on instantiation you require two underscores; __construct() how embarrassing for me , sometimes I guess just look to hard and make it all complex when the answer is obvious, thanks my good man/lady! Link to comment https://forums.phpfreaks.com/topic/163629-solved-class-within-a-class/#findComment-863368 Share on other sites More sharing options...
gevans Posted June 25, 2009 Share Posted June 25, 2009 Man Link to comment https://forums.phpfreaks.com/topic/163629-solved-class-within-a-class/#findComment-863370 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.