note 124990 deleted from language.oop5.references by cmb
| From: | cmb@php.net | Date: | Sat, 09 May 2020 16:15:58 +0000 |
| Subject: | note 124990 deleted from language.oop5.references by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-214599@lists.php.net to get a copy of this message | ||
Note Submitter: rnealxp at yahoo dot com
----
Two concise examples that illustrate the true difference between "object-assignment by
value" vs "object-assignment by reference":
<?php
class a{
public $a = 2;
}
class b{
public $b = 3;
}
//------------
//Code Set 1 (third line down does not use ampersand(&), it is an object assignment by copy):
$a = new a();
$b = new b();
$c = $a; //<--copy by value.
echo $c->a . "\n"; //output: 2
$a = $b; //This assignment has no affect on $c.
echo $c->a . "\n"; //output: 2 ($c is still a copy of $a, so this works)
echo $c->b . "\n"; //output: "Undefined property: a::$b" ($c is still a copy
of $a (not $b), so this does not work)
//------------
//Code Set 2 (third line down DOES use ampersand(&), it is an object assignment by
reference/pointer):
$a = new a();
$b = new b();
$c = &$a; //<--copy by reference/pointer.
echo $c->a . "\n"; //output: 2
$a = $b; //This assignment replaces $c's underlying object value.
echo $c->a . "\n"; //output: "Undefined property: b::$a" ($c is no longer a
copy of $a, so this does not work)
echo $c->b . "\n"; //output: 3 ($c now points to $b, so this works)
//------------
?>