|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2000-03-03 14:50 UTC] sas at cvs dot php dot net
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Tue Oct 28 19:00:01 2025 UTC |
There appears to be an odd behavior when it comes to passing objects by reference. Instead of passing the address of the object, it passes a copy of the object. This is unless I'm doing something wrong (not me #:-) )? Note that the following code has class that contains a second class. There is a method on the first class (foo) to return the reference of the object (bar) contained within it. You can get the reference to the object okay and the attributes of the object (bar) contains the correct information. If you call a modifier method on the 2nd reference to the object bar, it only updates that reference and not the object contained in the parent object foo. <pre> <?php // test.php class foo { var $x; var $bar; function foo($x=0, $y=0) { $this->setX($x); $this->bar = new bar($y); } function setX($val) { $this->x = $val; } function getX() { return $this->x; } function getY() { return $this->bar->getY(); } function getBar(&$objref) { $objref = $this->bar; } } class bar { var $y; function bar($y) { $this->setY($y); } function setY($y) { $this->y = $y; } function getY() { return $this->y; } } $a = new foo(12,33); print "<b>Initial values:</b><br>"; printf("a = [%d,%d]<br>\n", $a->getX(), $a->getY()); print "<b>Updated values:</b><br>"; $a->setx(234); printf("a = [%d,%d]<br>\n", $a->getX(), $a->getY()); print "<b>Updating 2nd Reference of Object (y=7777):</b><br>"; // Get the reference to object bar. $a->getBar($b); $b->setY(7777); printf("b = [%d]<br>\n", $b->getY()); printf("a = [%d,%d]<br>\n", $a->getX(), $a->getY()); // Note that a->y->y is not modified. ?> </pre>