|
Posted by davidgregan@gmail.com on 01/22/08 20:29
On Jan 22, 12:40 pm, Michael Fesser <neti...@gmx.de> wrote:
> .oO(davidgre...@gmail.com)
>
> >Hi, I'm fairly new to PHP and I have a question regarding pointers.
> >Below is an example binary tree implementation I found in the
> >internet. It works great but I'm not sure how it works. Here's what
> >I'm confused about, in the insert function the variable $pointer is
> >set to $this->tree. Now, my current understanding is that after this
> >the variable $pointer will contain the data from $this-> tree.
>
> Nope. The tree is built with objects and objects in PHP 5 are always
> addressed by a kind of reference (internally it's just a numeric handle
> that identifies the object). So with
>
> $pointer = $this->tree;
>
> both variables simply reference the same root node of the tree. There's
> still only one tree of objects.
>
> >However, as the function continues $pointer is set to pointer->left
> >(or right) until the correct index is found. at this point the value
> >is added to the tree with $pointer->left=new leaf.
>
> >In this case the value of pointer seems to be referencing a position
> >in the $tree variable
>
> Correct.
>
> >instead of merely containing the data of $tree
> >as I would expect. Furthermore, when $pointer->left is set to a new
> >leaf, it is actually added to $tree and not just to $pointer.
>
> Correct. $pointer always references a node of the tree. All of them are
> of the class 'leaf' and have the defined properties. So regardless which
> node is referenced by the $pointer variable, there's always a $data,
> $left and $right property.
>
> >So my
> >question is, why is this variable behaving like a pointer in this case
> >instead of just containing the value of tree?
>
> Try to understand how objects are handled and addressed in PHP 5:
>
> $foo = new Test();
> $bar = $foo;
>
> The first line creates a new object and assigns its internal number (the
> object handle, for example 42) to $foo, hence $foo kinda references the
> object with the internal number 42.
>
> The second line simply copies the number stored in $foo to $bar, so now
> both variables have the same value and therefore reference the same
> object. The object itself is never copied unless you explicitly clone
> it:
>
> $foo = new Test();
> $bar = clone $foo;
>
> Now both variables reference _different_ objects.
>
> Micha
Thanks a bunch, that clears things up!
Dave
Navigation:
[Reply to this message]
|