Apr 06 2010

PHP Quiz: Passing Objects By Value vs. Reference

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:

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: too low
Bar: too high

C:

Bar: low
Bar: too low
Bar: too high

D:

Parse/syntax error

E:

None of the above

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Twitter

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment