Editor’s Note: This article was originally posted at my personal site. I am re-posting it here because it is more appropriately placed in this blog.
Here is something to test your knowledge of how PHP handles passing objects by value vs. reference. Try to figure this out without using a PHP interpreter.
What is the output of the following code:
<?php class Foo { private $bar; public function Foo($x) { $this->bar = $x; } public function getBar() { return $this->bar; } public function setBar($x) { $this->bar = $x; } } function changeFooByValue($foo) { $foo->setBar('high'); $foo = new Foo('too low'); } function changeFooByRef(&$foo) { $foo->setBar('just high enough'); $foo = new Foo('too high'); } $foo = new Foo('low'); echo "Bar: " . $foo->getBar() . "n"; changeFooByValue($foo); echo "Bar: " . $foo->getBar() . "n"; changeFooByRef($foo); echo "Bar: " . $foo->getBar() . "n"; ?>
Is it:
A:
Bar: low Bar: too low Bar: too high
B:
Bar: low Bar: high Bar: too high
C:
Bar: low Bar: too low Bar: just high enough
D:
Parse/syntax error
E:
None of the above