Hi all,
I've noticed something strange with returning references, both in PHP4 and
5 - maybe it's supposed to do this, I don't know - but it seems a bit weird
nonetheless. Say we have the following test code:
<?php
class Test
{
var $foo = 12345;
function setFoo($foo=null)
{
$this->foo = $foo;
}
function &getFoo()
{
return $this->foo;
}
}
$test =& new Test();
$foo =& $test->getFoo();
$foo = 54321;
print_r($test);
?>
Upon execution, we should receive the following output:
test Object ( [foo] => 54321 )
....as we returned a reference to the foo attribute, and then changed it by
assigning 54321 to $foo. The PHP documentation is quite adamant that to
return by reference you need to have an ampersand both on the function
definition, and the variable assignment, and in this case that is true. If
you remove the ampersand from the getFoo() function definition above, you
will receive the following output:
test Object ( [foo] => 12345 )
....as a copy of the attribute and not a reference has been returned.
Now, what if we change the code to this:
<?php
class Test
{
var $foo = null; // <--- attribute is now NULL by default
function setFoo($foo=null)
{
$this->foo = $foo;
}
function &getFoo()
{
return $this->foo;
}
}
$test =& new Test();
$test->setFoo(12345); // <--- now using setter function to set foo
attribute to 12345
$foo =& $test->getFoo();
$foo = 54321;
print_r($test);
?>
Upon execution, we should receive the same result as before:
test Object ( [foo] => 54321 )
But if the ampersand is now *removed* from the getFoo() function definition,
it still returns by reference, and you receive the same result:
test Object ( [foo] => 54321 )
What am I missing?
--
{RainmakeR}