October 02, 2004

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.]

Technorati tags: PHP objects | pass by reference | objects | PHP | pass by value |

src="http://feeds.feedburner.com/~s/ChaosMagnet?i=http://www.chaosmagnet.com/blog/archives/000480.html" type="text/javascript" charset="utf-8">
Posted by roadnick at October 2, 2004 05:18 PM | TrackBack

Comments

What about:

function setObject(&$newObject){
$this->theObject =& $newObject;
}


It is late, my PHP machine is powered down for the night. I.e., correctness of this solution is left as an exercise for the reader.

HTH,
Jeffrey

Posted by: Jeff Taylor at October 4, 2004 01:30 AM

PHP5 does this by default :)

Posted by: The Wolf at October 11, 2004 07:32 PM

Please keep the PHP tips coming, we also like the article on tutorials.

Also, I have PHP4 not upgraded to version five yet. :)

Posted by: CarlosX at October 22, 2004 11:28 AM

Thanks! I'm thinking about expanding that tutorials piece, actually ...

---- Nick

Posted by: Nick at October 24, 2004 01:44 PM
Post a comment









Remember personal info?