note 91627 added to language.oop5.references

From: Date: Sat, 20 Jun 2009 01:08:54 +0000
Subject: note 91627 added to language.oop5.references
Groups: php.notes 
Request: Send a blank email to php-notes+get-157152@lists.php.net to get a copy of this message
I've bumped into a behavior that helped clarify the difference between objects and identifiers for me. When we hand off an object variable, we get an identifier to that object's value. This means that if I were to mutate the object from a passed variable, ALL variables originating from that instance of the object will change. HOWEVER, if I set that object variable to new instance, it replaces the identifier itself with a new identifier and leaves the old instance in tact. Take the following example: <?php class A { public $foo = 1; } class B { public function foo(A $bar) { $bar->foo = 42; } public function bar(A $bar) { $bar = new A; } } $f = new A; $g = new B; echo $f->foo . "\n"; $g->foo($f); echo $f->foo . "\n"; $g->bar($f); echo $f->foo . "\n"; ?> If object variables were always references, we'd expect the following output: 1 42 1 However, we get: 1 42 42 The reason for this is simple. In the bar function of the B class, we replace the identifier you passed in, which identified the same instance of the A class as your $f variable, with a brand new A class identifier. Creating a new instance of A doesn't mutate $f because $f wasn't passed as a reference. To get the reference behavior, one would have to enter the following for class B: <?php class B { public function foo(A $bar) { $bar->foo = 42; } public function bar(A &$bar) { $bar = new A; } } ?> The foo function doesn't require a reference, because it is MUTATING an object instance that $bar identifies. But bar will be REPLACING the object instance. If only an identifier is passed, the variable identifier will be overwritten but the object instance will be left in place. ---- Server IP: 209.41.74.194 Probable Submitter: 216.36.87.229 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.references.php Edit -- https://master.php.net/note/edit/91627 Del: integrated -- https://master.php.net/note/delete/91627/integrated Del: useless -- https://master.php.net/note/delete/91627/useless Del: bad code -- https://master.php.net/note/delete/91627/bad+code Del: spam -- https://master.php.net/note/delete/91627/spam Del: non-english -- https://master.php.net/note/delete/91627/non-english Del: in docs -- https://master.php.net/note/delete/91627/in+docs Del: other reasons-- https://master.php.net/note/delete/91627 Reject -- https://master.php.net/note/reject/91627 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#157152) next »