Webeks.net - freelance programming
freelance programming - php, Joomla, Zend ...
Home :: Articles :: Programming :: PHP :: ampersand (&) operator - used for assigning reference

ampersand (&) operator - used for assigning reference

Written by Miha

References in PHP are a means to access the same variable content by different names. They are not like C pointers; for instance, you cannot perform pointer arithmetic using them, they are not actual memory addresses, and so on. They could be described as symbol table aliases. In PHP variable name and variable content are different - the same content can have different names.

Pass-by-value

$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:

 


blog comments powered by Disqus