Page 1 of 1

[SOLVED] Classes and scope

Posted: Wed Dec 08, 2004 6:44 pm
by magicrobotmonkey
Ok here is the scenario. I have one class, lets call it 'dad' and another class 'junior'. Either 'dad' or 'junior' can be used directly from various scripts. If dad is used, he will create a bunch of 'juniors' (heh).

I also have a class 'db' which is a database abstraction class.

The 'dad' and 'junior' classes will be called from scripts which may or may not be using the db abstraction class so I can't assume that I will be passed this class.

So whats the best way to even do this? Is just passing it to the constructor good? What if I pass it by reference (thats what I think is best). Is there another way to make the 'db' class accessible to everyone? I dont want to automatically build a 'db' class in everyone of these, because it will create a lot of overhead.

is it right to do something like this:


Code: Select all

<?php

class dad 
{
    var $db;

    function dad(&$thisDB)
    {
        if(!is_object($thisDB))
        {
             include(db.class.php)
              $this->db = new db($connectinfo)

        }
        else
              $this->db = $thisDB
    }


}

?>
*sigh* I'm not sure what to do....

Posted: Wed Dec 08, 2004 6:51 pm
by kettle_drum
Yeah thats fine, i always pass class references to other classes, and do it just like this - using an array of class objects if i have to pass more than one.

Posted: Thu Dec 09, 2004 8:36 am
by Maugrim_The_Reaper
Solved in your own post - :). Passing the object by reference is just fine - I certainly don't use anything else...

Posted: Thu Dec 09, 2004 2:50 pm
by McGruff
If you're using php4:

Code: Select all

$foo =& new Foo;

function foo(&$object)
{
    $this->foo =& $object;
}

function &getFoo()
{
    return $this->foo;

    // or:
    return new Foo;
}

Posted: Thu Dec 09, 2004 7:03 pm
by magicrobotmonkey
now you've gone over my head

Code: Select all

<?php

//"create by reference??" whats this one do?
$foo =& new Foo;

function foo(&$object)
{
    //isn't the one in the function parameter list enough or is this one needed as well?
    $this->foo =& $object;
}


//what does it mean to pur this on a function?
function &getFoo()
{
    return $this->foo;

    // or:
    return new Foo;
}
?>