views:

400

answers:

5

If I create an object inside of the main scope:

INDEX.PHP:

$db = new database();

Then how can I use this same object inside of a completely different class?

ANYTHING.PHP:

class anything {
    function __construct(){
        $db->execute($something); # I want to use the same object from INDEX.PHP
    }
}

Would I need to make $db a global or is there a 'better' more obvious way?

+1  A: 

You could just use global to find it:

class anything {
    function __construct(){
        global $db;
        $db->execute($something);
    }
}

Or, you could pass it in when creating a new anything:

class anything {
    function __construct($db) {
        $db->execute($something);
    }
}

It really depends on what makes the most sense for you.

Paolo Bergantino
If I were doing it, I would pass the object into the constructor instead of using the global keyword.
scheibk
A: 

You could pass it as an argument, like this

function __construct($db){
   $db->execute($something);
}

then when you instance anything, do it as anything($db)

ONi
A: 

As Paolo and ONi suggested you can define $db as global inside the method or pass it into the constructor of the class. Passing it in will create a reference to that object so it will in fact be the same $db object. You could also use the $GLOBALS array and reference $db that way.

$GLOBALS["db"];

I'm assuming that index.php and anything.php are linked together somehow by include() or require() or some similar method?

Crazy Joe Malloy
Yep, I'm using the __autoload() function. Thanks for your help.
Dax
No problem, glad to be of service :)
Crazy Joe Malloy
A: 

In Paolo's post:

After you pass it, you can then assign it to a class variable like this:

class anything {
    var $db_obj;
    function __construct($db) {
        $this->db_obj = $db;
    }

    function getUsers() {
        return $this->db_obj->execute($something);
    }
}
marknt15
+1  A: 

For the DB you may want to use Singleton pattern

class anything 
{
    public function load($id)
    {
        $db = DB::getInstance();
        $res = $db->query('SELECT ... FROM tablename WHERE id = '.(int)$id);
        // etc...
    }
}

You may want to extend it if you need different DB connections at the same time (i.e main db and forum's db). Then you'll use it like DB::getInstance('forum'); and store instances in associative array.

Jet