note 49877 added to language.oop.newref

From: Date: Fri, 11 Feb 2005 01:24:07 +0000
Subject: note 49877 added to language.oop.newref
Groups: php.notes 
Request: Send a blank email to php-notes+get-84820@lists.php.net to get a copy of this message
Regarding the use of assignment versus reference operators as they pertain to using classes which register shutdown functions. Here's an example: <?php class testclass { var $value; function testclass() { register_shutdown_function(array(&$this, 'tcshutdown')); $this->value = 1; print 'Construction value=[' . $this->value ."]\n"; } function setvalue($value) { $this->value = $value; } function tcshutdown() { print 'Shutdown value=[' . $this->value ."]\n"; } } $testobj = new testclass(); $testobj->setvalue(2); ?> Despite changing the value to 2 after the object is constructed, the above code will result in the following output: Construction value=[1] Shutdown value=[1] The reason is new testclass() constructs the object and registers tcshutdown function from that copy of the object. Then assigning it to $testobj makes a copy of the object accessible as $testobj. Altering $testobj values confines those changes to the $testobj copy and doesn't affect the original ("new") copy of the object. When shutdown time comes around and the tcshutdown() function is called, it calls the original ("new") copy of tcshutdown() NOT $testobj's copy. Thus tcshutdown() sees only the original member value that was initialized by the constructor before the object was copied to $testobj. The way to resolve this is to, again, convert from assignment to a reference with the following alteration: <?php $testobj =& new testclass(); ?> With that change, running the code again will result in what we expected: Construction value=[1] Shutdown value=[2] This of course allows the tcshutdown() function to perform shutdown operations based on parameters which were altered subsequent to the construction of the object. ---- Manual Page -- http://www.php.net/manual/en/language.oop.newref.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+49877 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+49877&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+49877&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+49877&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+49877&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+49877&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+49877&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#84820) next »