Re: references-weirdness???
| From: | Lars Torben Wilson | Date: | Wed, 28 Nov 2001 23:39:32 +0000 |
| Subject: | Re: references-weirdness??? | ||
| References: | 1 | Groups: | php.dev |
| Request: | Send a blank email to php-dev+get-71970@lists.php.net to get a copy of this message | ||
Wolfram Kriesing writes:
> why do the following two examples result in different things, even
> though i would expect the same behaviour?
From the manual:
http://www.php.net/manual/en/language.references.return.php
function &find_var ($param)
{
...code...
return $found_var;
}
$foo =& find_var ($bar);
$foo->x = 2;
In this example, the property of the object returned by the find_var
function would be set, not the copy, as it would be without using
reference syntax.
Note: Unlike parameter passing, here you have to use & in both
places - to indicate that you return by-reference, not a copy as
usual, and to indicate that reference binding, rather than usual
assignment, should be done for $foo.
...in other words, your problem is here:
> $test = new test;
> // but this one does NOT !!!
> $walk = $test->getData(0);
^^^
...it should be:
$walk =& $test->getData(0);
> $walk = $test->data[1];
> print('<br>');
> print_r($test);
Cheers,
Torben
> in words: i pass a reference of a class-property to a variable $walk,
> if i overwrite $walk, the class-property has a new value too (seems
> logical, since we are working with references not pointers)
> BUT
> if i use a class-method which returns a reference to this
> class-property, to set $walk ... and then i overwrite $walk the
> class-property didnt change
>
>
> code-example
> <?php
>
> class test
> {
> var $data;
> function test()
> {
> $this->data[0] = 'level zero';
> $this->data[1] = 'level one';
> }
>
> function &getData( $id )
> {
> return $this->data[$id];
> }
> }
>
> $test = new test;
> print('<br>');
> print_r($test);
>
> // the following block overwrites $test->data[0] with $test->data[1]
> $walk = &$test->data[0];
> $walk = $test->data[1];
> print('<br>');
> print_r($test);
>
>
> $test = new test;
> // but this one does NOT !!!
> $walk = $test->getData(0);
> $walk = $test->data[1];
> print('<br>');
> print_r($test);
>
> ?>
>
> --
> Wolfram
>
> --
> PHP Development Mailing List <http://www.php.net/>
> To unsubscribe, e-mail: php-dev-unsubscribe@lists.php.net
> For additional commands, e-mail: php-dev-help@lists.php.net
> To contact the list administrators, e-mail: php-list-admin@lists.php.net
>
--
Torben Wilson <torben@php.net>
http://www.thebuttlesschaps.com
http://www.hybrid17.com
http://www.inflatableeye.com
+1.604.709.0506