Skip to content

Instantly share code, notes, and snippets.

@jehoshua02
Created October 16, 2011 05:59
Show Gist options
  • Select an option

  • Save jehoshua02/1290560 to your computer and use it in GitHub Desktop.

Select an option

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.
@YMas
Copy link
Copy Markdown

YMas commented Oct 16, 2011

Hello, you left ##php before I could reply to your query, I suggest you look at this man page and modify your code accordingly:

http://php.net/manual/en/language.references.return.php

@jehoshua02
Copy link
Copy Markdown
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