$object1 = new SomeClass();
$object2 = $object1;
$property1 = "X";
$property2 = $property1;
Now I have objects of the same class but they are independent from each other. If I change propertyX of the $object1 propertyX of $object2 will stay unchanged. This is so called pass-by-value behavior that was default behavior in PHP 4. We could enforce pass-by-reference bahavior with use of ampersand operator &. In PHP 5 default behavior changed a bit (btw. thanks for correcting me Phil!). Objects in PHP 5 will be passed as references (this does not apply for variables).References in PHP are a means to access the same variable content by different names.
Assign by reference
$object1 = new SomeClass();
$object2 = & $object1;
$object1 and $object2 are completely equal here. $object1 is not pointing to $object2 or vice versa. $object1 and $object2 are pointing to the same place.
Pass by reference
class Foo {
public $bar;
function setBar( & $varBar) {
$this->bar = & $bar;
}
}
$v1 = "test";
$foo = new Foo();
$foo->setBar($v1);
$v1 = "test123";
echo $foo->bar; //echoes test123
There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in $foo->setBar("xxx").
Return by reference
class Foo {
public $bar;
function &getBar() {
return $this->bar;
}
}
$v1 = "test";
$foo = new Foo();
$foo->bar = &$a;
$v2 = &$foo->getBar();
$v1 = "test123";
echo $v2; //echoes test123
Pass object by value - PHP 5
Creating a copy of an object with fully replicated properties was a default behavior back in PHP4. In PHP5 we have to enforce passing-by-value. This is done by cloning. An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly.$copy_of_object = clone $object;
Further reading:
Email this
Hits: 2164
Comments (4)

Write comment


