对象传递:一种说法是“PHP对象是通过引用传递的”,更准确的说法是别名(标识符)传递,即它们都保存着同一个标识符(ID)的拷贝,这个标识符指向同一个对象的真正内容,与引用(&)有质的区别,请比较下例中行11和行18的输出结果。
1 <?php 2 class A { 3 public $foo = 1; 4 } 5 6 $a = new A; 7 $b = $a; // $a ,$b都是同一个标识符的拷贝 ($a) = ($b) = <id> 8 $b->foo = 2; 9 echo $a->foo."\n";//210 $b = null;11 echo $a->foo."\n";//212 13 $c = new A;14 $d = &$c; // $c ,$d是引用 ($c,$d) = <id>15 $d->foo = 2;16 echo $c->foo."\n";//217 $d = null;18 echo $c->foo."\n";//Notice: Trying to get property of non-object19 20 $c = new A;21 $d = &$c; // $c ,$d是引用 ($c,$d) = <id>22 $d->foo = 2;23 echo $c->foo."\n";//224 unset($d); //unset()删除引用,$c = <id>25 echo $c->foo."\n";//226 27 $e = new A;28 function foo($obj) {29 // ($obj) = ($e) = <id>30 $obj->foo = 2;31 }32 foo($e);33 echo $e->foo."\n";//2