note 49877 deleted from language.oop.newref by danbrown
| From: | danbrown@php.net | Date: | Sat, 07 Nov 2009 19:11:09 +0000 |
| Subject: | note 49877 deleted from language.oop.newref by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-162583@lists.php.net to get a copy of this message | ||
Note Submitter: info at keenkelly dot com
----
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.