Tips:点此可运行HTML源码

深入理解PHP对象赋值

 1 <?php 
2
//深入理解PHP对象赋值 3 echo '<pre>'; 4 5 $obj = new StdClass; 6 $obj->name = 'Pig'; 7 var_dump($obj);  //object(stdClass)#1 (1) { ["name"]=> string(3) "Pig" } 8 9 $copy = $obj;   // $obj ,$copy都是new StdClass返回的同一个标识符的拷贝 10 var_dump($copy);    //object(stdClass)#1 (1) { ["name"]=>string(3) "Pig" } 11 12 $objRef = &$obj;    // 此时会将$obj转换成引用,然后赋值给$objRef,因此$obj,$objRef都为引用 13 var_dump($objRef); //object(stdClass)#1 (1) { ["name"]=>string(3) "Pig" } 14 15 $objClone = clone $obj; //新空间 16 $obj->name = 'After Clone'; 17 var_dump($objClone);   //object(stdClass)#1 (1) { ["name"]=>string(3) "Pig" } 18 var_dump($obj); //object(stdClass)#1 (1) { ["name"]=>string(11) "After Clone" } 19 20 //unset是删除引用效果 21 $nameRef = &$obj->name; //$obj->name被转换成引用(& string),然后赋给$nameRef 22 var_dump($obj); //object(stdClass)#2 (1) { ["name"]=>&string(11) "After Clone" } 23 unset($nameRef);   //删除引用 24 var_dump($obj); //object(stdClass)#1 (1) { ["name"]=>string(11) "After Clone" } 25 26 //null是赋值效果 27 $nameRef = &$obj->name; //恢复name的引用 28 var_dump($obj); //object(stdClass)#2 (1) { ["name"]=>&string(11) "After Clone" } 29 $nameRef = null; 30 var_dump($obj); //object(stdClass)#2 (1) { ["name"]=>&NULL } 31 32 unset($objRef); //仅仅删除了引用 33 var_dump($obj); //object(stdClass)#1 (1) { ["name"]=>&NULL } 34 35 $objRef = &$obj;   //恢复对象引用 36 $obj->name = 'Lucy'; 37 $obj = null;   //赋值$obj为null,$obj只是new StdClass的标识拷贝,不会影响其内容。 38 //$objRef做为$obj的引用,会同时被赋值null 39 //等价 $objRef = null; 40 41 var_dump($obj,$copy,$objRef,$objClone); 42 // NULL, 43 // object(stdClass)#1 (1) { ["name"]=>&string(4) "Lucy" }, 44 // NULL, 45 // object(stdClass)#1 (1) { ["name"]=>string(3) "Pig" } 46 47 ?>

 

posted @ 2013-01-03 15:57  Zjmainstay  阅读(11400)  评论(1编辑  收藏  举报