ballhogjoni Posted September 1, 2013 Share Posted September 1, 2013 I didn't right this code but I can't figure out why the $db var isn't available in the DBPersister() constructor and in the functionName(). $s = new somePersister(); print_r($s->functionName(123)); class somePersister extends DBPersister { public function functionName($id) { ... do stuff ... print_r($this->db); //DOES NOT print DB instance } } <?php include_once('db.inc.php'); print_r($db); //prints the DB instance class DBPersister { var $db; function DBPersister() { global $db; print_r($db); //DOES NOT print the DB instance $this->db =& $db; } } db.inc.php class DB extends _Database_ { var $host; var $dbname; var $user; var $password; var $result; var $record; var $connected; function DB() { $this->_Database_(); $this->host = DATABASE_HOST; $this->dbname = DATABASE_NAME; $this->user = DATABASE_USERNAME; $this->password = DATABASE_PASSWORD; } } $db = new DB(); Quote Link to comment Share on other sites More sharing options...
Irate Posted September 1, 2013 Share Posted September 1, 2013 As someone with a high status here says in their signature... "Using global is a sign of doing it wrong." So, because this is necessary, where do you want to have $db defined? Everywhere in your class? Everywhere in PHP? Quote Link to comment Share on other sites More sharing options...
AbraCadaver Posted September 1, 2013 Share Posted September 1, 2013 (edited) No globals, especially in OOP. You should start using the PHP 5 __functions() and private, protected and public vars and methods. This may not be perfect but better, and just to show the concept: include_once('db.inc.php'); $s = new somePersister($db); print_r($s->functionName(123)); class DBPersister { public $db; public function __construct($db) { $this->db = $db; } } class somePersister extends DBPersister { public function __construct($db) { //... do stuff ... parent::__construct($db); } public function functionName($id) { //... do stuff ... print_r($this->db); } } Or you could use a registry class/object and store the $db object there and the DBPersister could grab it from the registry in the __construct(). Edited September 1, 2013 by AbraCadaver Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.