On Thu, 30 Oct 2003 22:54:49 +0100, you wrote:
>Hi there,
>
>I'm having trouble with passing objects as references. What I want to
>do is something like this:
[snip code]
>The above code give the output:
>
>instance:
>parent: test
>
>where I want it to give:
>
>instance: test
>parent: test
I don't pretend to fully understand PHP references, or the strange and
mysterious ways that they work in regards to PHP objects, but I can
tell you how to acheive the results you desire. Someone else will
have to explain it. :)
First of all, you need to use the "=&" operator inside the constructor
for object_2. Secondly, you need to use the same "=&" operator when
creating the new instance of object_1. Full code follows:
class object_1
{
var $my_child;
var $my_array;
function object_1()
{
$this->my_array = array('id' => 0, 'name'=>'');
$this->my_child = new object_2($this);
}
}
class object_2
{
var $my_parent;
function object_2(&$parent_object)
{
$this->my_parent =& $parent_object;
}
function set_parent()
{
$this->my_parent->my_array['id'] = 1;
$this->my_parent->my_array['name'] = 'test';
}
}
$instance =& new object_1();
$instance->my_child->set_parent();
echo "instance: ".$instance->my_array['name']."<br>";
echo "parent:
".$instance->my_child->my_parent->my_array['name']."<br>";
This outputs (on PHP 4.3.3):
instance: test
parent: test
Alternatively, you can forgo the "=&" operator when creating a new
instance of object_1 if you move the creation of the object_2 child
out of object_1's constructor and into another method. Say we add
this method to object_1:
function create_my_child() {
$this->my_child = new object_2($this);
}
Then you can do this:
$instance = new object_1();
$instance->create_my_child();
$instance->my_child->set_parent();
echo "instance: ".$instance->my_array['name']."<br>";
echo "parent:
".$instance->my_child->my_parent->my_array['name']."<br>";
This also outputs:
instance: test
parent: test
I really can't explain why either of these approaches work, but I
suspect that it has something to do with the phenomenon described
here:
http://www.php.net/manual/en/language.oop.newref.php
The headache I currently have prevents me from fully understanding
this, hopefully it will be clearer to you. :)
If someone sees that I'm leading Gareth astray here, feel free to jump
in and correct me...
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php