note 109048 added to language.references.pass
| From: | DavidR | Date: | Fri, 15 Jun 2012 15:45:27 +0000 |
| Subject: | note 109048 added to language.references.pass | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-188628@lists.php.net to get a copy of this message | ||
One thing I reckon is simple but pretty cool is that if you take a reference from a reference, they
both point to the same thing original variable (as you would hopefully expect).
This means you can pass in a variable (by reference), and then make a reference from that, you can
make changes to the original variable later.
<?php
class DelayedChange {
private $changeTarget;
public function prepareForChange(&$target) {
// Save a reference to the variable we want to change
$this->changeTarget = &$target;
}
public function change($value) {
// Assign a new value
$this->changeTarget = $value;
}
}
$testVar = "value 1";
$delayedChange = new DelayedChange();
$delayedChange->prepareForChange($testVar);
echo ($testVar."<br>\n"); // outputs "value 1"
$delayedChange->change("value 2");
echo ($testVar."<br>\n"); // outputs "value 2"
?>
(naturally, this only works if you make $changeTarget a reference - if you just write
"$this->changeTarget = $target" then it copies $testVar's value instead of taking
a new reference to it.)
----
Server IP: 69.147.83.197
Probable Submitter: 195.166.29.2
----
Manual Page -- http://www.php.net/manual/en/language.references.pass.php
Edit -- https://master.php.net/note/edit/109048
Del: integrated -- https://master.php.net/note/delete/109048/integrated
Del: useless -- https://master.php.net/note/delete/109048/useless
Del: bad code -- https://master.php.net/note/delete/109048/bad+code
Del: spam -- https://master.php.net/note/delete/109048/spam
Del: non-english -- https://master.php.net/note/delete/109048/non-english
Del: in docs -- https://master.php.net/note/delete/109048/in+docs
Del: other reasons-- https://master.php.net/note/delete/109048
Reject -- https://master.php.net/note/reject/109048
Search -- https://master.php.net/manage/user-notes.php