A key point often mentioned in object programming in php5 is that "objects are passed by reference by default". But actually this is not entirely correct. Here are some examples to illustrate.
PHP references are aliases, that is, two different variable names point to the same content. In PHP5, an object variable no longer holds the value of the entire object. Just save an identifier to access the real object content. When an object is passed as a parameter, returned as a result, or assigned to another variable, the other variable has no reference relationship with the original one, but they both store a copy of the same identifier, which points to the real content of the same object. .
Example #1 References and objects
<?php class A { public $foo = 1; } $a = new A; $b = $a; // $a ,$b都是同一个标识符的拷贝 // ($a) = ($b) = <id> $b->foo = 2; echo $a->foo."\n"; $c = new A; $d = &$c; // $c ,$d是引用 // ($c,$d) = <id> $d->foo = 2; echo $c->foo."\n"; $e = new A; function foo($obj) { // ($obj) = ($e) = <id> $obj->foo = 2; } foo($e); echo $e->foo."\n"; ?>
The above routine will output:
2 2 2