:::: MENU ::::

PHP and passing object by reference

It is not really that we are passing object instances in PHP by reference. It is a little bit tricky, but the manual has this covered!

As of PHP 5, an object variable doesn’t contain the object
itself as value anymore. It only contains an object identifier which allows
object accessors to find the actual object. When an object is sent by
argument, returned or assigned to another variable, the different variables
are not aliases: they hold a copy of the identifier, which points to the same
object.

<?php 
class A { 
	public $foo = 1; 
} 

$a = new A; 
$b = $a; 
$a->foo = 2;
$a = NULL;
echo $b->foo."\n"; // 2

$c = new A;
$d = &$c;
$c->foo = 2;
$c = NULL;
echo $d->foo."\n"; // Notice:  Trying to get property of non-object…
?>

Pages:12345