PHP5 objects assigned by reference?
I’ve been working with PHP5 since it’s release and find it very hard to believe I haven’t come across this yet. By default, in PHP5, assigning an object instance to another variable, the new variable will access the same instance, but not by reference? To quote the manual:
When assigning an already created instance of an object to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A new instance of an already created object can be made by cloning it.Hence the code… <?php class
REXML could not parse this XML/HTML: </span>
var </span>$myVariable = '1'; }
$instance1REXML could not parse this XML/HTML: </span>
REXML could not parse this XML/HTML: </span>
REXML could not parse this XML/HTML: </span>$assignNormally
REXML could not parse this XML/HTML: </span>var_dump
REXML could not parse this XML/HTML: </span>
REXML could not parse this XML/HTML: </span>
REXML could not parse this XML/HTML: </span>$instance1 var_dump
REXML could not parse this XML/HTML: </span>
REXML could not parse this XML/HTML: </span>
REXML could not parse this XML/HTML: </span>?>
Produces …
object(MyClass)#1 (1) {
["myVariable"]=>
string(1) "2"
}
object(MyClass)#1 (1) {
["myVariable"]=>
string(1) "2"
}
object(MyClass)#1 (1) {
["myVariable"]=>
string(1) "2"
}
object(MyClass)#2 (1) {
["myVariable"]=>
string(5) "clone"
}
NULL
object(MyClass)#1 (1) {
["myVariable"]=>
string(1) "2"
}
NULL
object(MyClass)#2 (1) {
["myVariable"]=>
string(5) "clone"
}
About
Dave Marshall is a Software Engineer living near Hull, England. He works on various personal projects and is the Technical Manager at Childcare.co.uk
Dave specialises in web application development for the LAMP stack, but always tries to choose a tool set that is most fit for purpose.
Dave is a Zend Certified Engineer and a Member of the British Computer Soceity.