Created
October 16, 2011 05:59
-
-
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?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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. |
Author
jehoshua02
commented
Oct 16, 2011
via email
Actually, the sample did exactly what I wanted it to do. Within the method,
I wanted the variable to be a reference of a class variable, but after
returning, I did not want the variable to reference the class variable.
The reason I create a variable reference is that I wanted a shorthand inside
the method.
But I don't want a reference after the method returns because I want to
protect class variables.
Thanks though!
That is a good reference from the php manual!
…On Sat, Oct 15, 2011 at 11:11 PM, Yousif Masoud < ***@***.***>wrote:
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
##
Reply to this email directly or view it on GitHub:
https://gist.github.com/1290560
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment