對象傳遞:一種說法是“PHP對象是通過引用傳遞的”,更準確的說法是別名(標識符)傳遞,即它們都保存著同一個標識符(ID)的拷貝,這個標識符指向同一個對象的真正內(nèi)容,與引用(&)有質(zhì)的區(qū)別,請比較下例中行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