Dax
Dax

Reputation: 83

How can I use a different object inside of a class?

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?

Upvotes: 0

Views: 3447

Answers (5)

Jet
Jet

Reputation: 1171

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.

Upvotes: 1

marknt15
marknt15

Reputation: 5127

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);
    }
}

Upvotes: 0

Crazy Joe Malloy
Crazy Joe Malloy

Reputation: 834

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?

Upvotes: 0

fixmycode
fixmycode

Reputation: 8506

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)

Upvotes: 0

Paolo Bergantino
Paolo Bergantino

Reputation: 488394

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.

Upvotes: 1

Related Questions