Skip to content

Instantly share code, notes, and snippets.

@jehoshua02
Created October 16, 2011 05:59
Show Gist options
  • Save jehoshua02/1290560 to your computer and use it in GitHub Desktop.
Save jehoshua02/1290560 to your computer and use it in GitHub Desktop.
What happens when I return a variable reference, then try to modify it?
<?php
// what happens when I return a reference to a variable, then try to modify it?
class ReferenceOrValue
{
private $variable;
public function __construct($value)
{
$this->variable = $value;
}
public function method()
{
$variable =& $this->variable;
return $variable;
}
public function getValue()
{
return $this->variable;
}
}
$value = 'Hello World!';
$object = new ReferenceOrValue($value);
$return = $object->method();
echo "Return should be '{$value}'.<br />"; // Return should be 'Hello World!'.
echo "Return is '{$return}'.<br />"; // Return is 'Hello World!'.
// if return is reference . . .
$before = $return;
$return = 'Hello Mars!';
$after = $object->getValue();
echo "Is '{$before}' the same as '{$after}'?"; // Is 'Hello World!' the same as 'Hello World!'?
// answer is nothing.
@jehoshua02
Copy link
Author

jehoshua02 commented Oct 16, 2011 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment