Jump to content

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

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?

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 by AbraCadaver
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.