Re: Storing a reference to an object in another object

From: Date: Wed, 19 Jan 2005 22:15:46 +0000
Subject: Re: Storing a reference to an object in another object
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-206778@lists.php.net to get a copy of this message
Rory McKinley wrote:
Hi All This is probably just a case of me being Mr Thicky, but maybe someone can point out the error mf my ways: I have two classes, call them admin and module. Admin stores login details as well as a pointer to the DB connection. Module will run various queries. To do that it needs access to the DB connection maintained by Admin. Because I don't want to have to keep on passing the reference to the admin instance, I thought I would store the reference to the admin instance within the module instance when the object is created: class Module {
    private $admin_instance;
    function __construct($admin_instance)
    {
        $this->admin_instance = $admin_instance;
    }
    public function checkConnection()
    {
        return $this->admin_instance->checkConnection()
    }
}
I assume this is not your actual code (by the manner in which you wrote above - '...,call them admin and...'). are you absolutely sure there is not a typo somewhere? like 'adnin_instance' or 'admin_imstance' you better off posting actual code snippets and removing sensitive data (assuming your allowed.)
I am using PHP 5 so the reference should be passed and stored in the relevant object attribute, not so?
correct :-) no. 1 benefit in php5 - proper objects.
Yet, if i call checkConnection it tells me that I am calling a method on
can you call the checkConnection() method in the __construct() of Module?
a non-object.print_r() of the module instance makes things even more confusing: print_r returns: [admin_instance:private] => [class_name] => blah [admin_instance] => Admin Object which is followed by the various attributes of the admin object suggesting that the reference to the admin object is indeed within the module instance. I hope someone can help with this..
I do this kind of thing the whole time (references to parent, application and subobjects - circular references not being a problem), I can't see that your doing anything wrong. though there is not much code to go on.
Oh, and before anybody asks I am still busy RTFM, STFW, STFA but with no
good for you :-)
joy so far.
bummer. post some more code ;-)


« previous php.general (#206778) next »