Programming tip: PHP objects as values
OK, here’s something that’s been holding me up for a little while. When you create an object in PHP and set it as a member of a second class, PHP actually creates a copy, rather than passing a reference to the original object. Any changes that you make to the original or to the copy do not get shared between them. To see that work, try running this script:
<?php
class Object1{
var $theObject;
function setObject($newObject){
$this->theObject = $newObject;
}
function getObject(){
return $this->theObject;
}
} class Object2{
var $theValue;
function setValue($newValue){
$this->theValue = $newValue;
}
function getValue(){
return $this->theValue;
}
}
$object1 = new Object1;
$object2 = new Object2;
$object2->setValue("One");
$object1->setObject($object2);
$tempObject = $object1->getObject();
echo "Value of embedded object is "
echo $tempObject->getValue()."</p>";
$object2->setValue("Two");
echo "<p>Set value of object2 to "
echo $object2->getValue()."</p>";
$tempObject = object1->getObject();
echo "Value of embedded object is "
echo $tempObject->getValue()."</p>";
?>
You should see a result of:
Value of embedded object is One
Set value of object2 to Two
Value of embedded object is One
As a corrolary to that, that means that there’s a difference between:
function setObjectValue($newValue){
$this->theObject->setValue($newValue);
}
and
function setObjectValue($newValue){
$tempobject = $this->theObject;
$tempobject->setValue($newValue);
}
Something to keep in mind.
[NOTE: In trying to figure something else out, I've run across a way to pass a variable by reference:
function myfunction(&$varname)
but that doesn't seem to help in this case.]
[NOTE on the NOTE: Problem solved by Jeffrey Taylor. Check out the comments for the solution.]
