Friday, June 5, 2009

Object references, assignment and as function arguments

As of PHP5, objects are treated REFERENCE ! (same behaviour as C++ and Java)

1) assignment from an objects to another copies the reference, not the content !!
What is a reference ? it's a variabile/object that ONLY contains the pointer to the effective object in the memory. As I said in a previous post, the assigment instruction copy ONLY the value (pointer) of the object-pointer, it doesn't duplicate the content (members) of the class !
Let's demonstrate with an example, using the unset() function

class A { public $foo = 1; }
$a = new A;
$aRef = $a;
unset($aRef ); //delete ONLY the object-pointer !
print $a->foo; //print 1. This is the proof that $aRef is only a pointer

$aRef = $a;
unset($aRef ->foo); //through the object-pointer $c, it delete the real content !!
print $a->foo; //Notice: Undefined property !! This is the proof that $aRef is not a copy !!

2) objects are passed to functions by REFERENCE !

class A { public $foo = 1; }
$a = new A;
function foo($obj) {
$obj->foo = 2;
unset($obj); // delete local reference (that is a copy), no problem !
}
foo($a);
echo $a->foo; //2 ! this is the proof that the argument is passed as reference (the function doesn't return any value !) and not as a copy (the value outside the function is changed!)


Note 1: arrays are passed by copy, unless the function declare the argument as reference with "&"
function arrayDeleteFirst(&$ar) { unset($ar[0]); }

Note2: references work with variables as well
$a = 1;
$b = &$a;
$b = 2;
unset($b); //no problem. It deletes the reference, not the variabile pointed !
print $a; //2

No comments:

Post a Comment

 

PHP and tips|PHP