note 56820 deleted from language.references.pass by googleguy

From: Date: Sun, 23 Feb 2014 17:13:56 +0000
Subject: note 56820 deleted from language.references.pass by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-198602@lists.php.net to get a copy of this message
Note Submitter: rmarscher ---- Not sure if this is obvious to everyone, but if you pass an object by reference into a function and then set that variable to the reference of a new object, the initial variable outside the function is still pointing to the original object. It became obvious to me why this is the case when I made a little diagram of what's actually happening in the system's memory, but before that when I was just looking at the code, it took me a while of testing before I realized what was going on. Here's an example (I haven't tried in PHP5, but I would guess it works the same): <?php class Foo {} class Bar {} function & createBar() { return new Bar; } function setBar(& $obj) { echo get_class($obj) . "\n"; $obj = & createBar(); echo get_class($obj) . "\n"; } $test = new Foo; setBar($test); echo get_class($test); ?> Outputs: foo bar foo

« previous php.notes (#198602) next »