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(); Link to comment https://forums.phpfreaks.com/topic/281762-variable-not-available-scope-issue/ 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? Link to comment https://forums.phpfreaks.com/topic/281762-variable-not-available-scope-issue/#findComment-1447705 Share on other sites More sharing options...
AbraCadaver Posted September 1, 2013 Share Posted September 1, 2013 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(). Link to comment https://forums.phpfreaks.com/topic/281762-variable-not-available-scope-issue/#findComment-1447708 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.