Jump to content

Variable not available? Scope issue?


ballhogjoni

Recommended Posts

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

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().

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.