clone() 方法生成被選元素的副本,包含子節點、文本和屬性。本文主要和大家分享PHP中引用以及clone的詳解,希望能幫助到大家。
<?php class Person{ private $name='personName'; public function __construct($name){ $this->name=$name; } public function showName(){ var_dump('current class is '.$this->name); } public function setName($name){ $this->name=$name; } public function getName(){ return $this->name; } } $xiaoming=new Person('xiaoming'); $xiaoming->showName();//current class is xiaoming //1.將對象賦值給一個變量時候 //對象引用的傳遞,即xiaoming和xiaoli指向的是同一個對象,改變任意一個對象,另一個對象也發生改變 $xiaoli=$xiaoming; $xiaoli->showName();//current class is xiaoming $xiaoli->setName("xiaoli"); $xiaoli->showName();//current class is xiaoli $xiaoming->showName();//current class is xiaoli $xiaoming->setName("xiaomingA"); $xiaoli->showName();//current class is xiaomingA $xiaoming->showName();//current class is xiaomingA //1.將對象作為參數傳遞時候 //如果將一個對象作為函數的實參傳遞,當改變形參對應的屬性的時候,對象的屬性也發生變化 function modifyObj($obj){ $obj->setName('modifyObj'); } modifyObj($xiaoming); $xiaoming->showName();//current class is modifyObj // 思考:可能有人會想,我僅僅是為了獲取對象的一個副本,并不想對原對象進行操作,該怎么辦呢? $xiaowang=clone $xiaoming;//注意,前提是在類中沒有重寫__clone()函數,且設置禁止對象被復制。 $xiaowang->showName();//current class is modifyObj $xiaowang->setName('xiaowang'); $xiaowang->showName();//current class is xiaowang $xiaoming->showName();//current class is modifyObj //總結:通過上面的現象說明了,php中雖然沒有指針的概念,但是卻和java類似,有了引用。 //關于PHP中的__clone(),我覺得有必要再次強調一下,php的__clone()方法對一個對象實例進行的淺復制,對象內的基本數值類型進行的是傳值復制,而對象內的對象型成員變量,如果不重寫__clone方法,顯式的clone這個對象成員變量的話,這個成員變量就是傳引用復制,而不是生成一個新的對象,直接通過實例演示 class Student{ private $name='someStudent'; private $person=null; public function __construct($name,$person){ $this->name=$name; $this->person=$person; } public function showName(){ var_dump('current Student class is '.$this->name.' ,current Person class is '.$this->person->getName()); } public function setName($name){ $this->name=$name; } public function setPersonName($name){ $this->person->setName($name); } public function __clone(){ $this->person=clone $this->person; } } $stu1=new Student('stu1',$xiaowang); $stu1->showName();//current Student class is stu1 ,current Person class is xiaowang $stu2=clone $stu1; $stu2->setName('stu2'); $stu2->setPersonName('stu2_persion'); $stu2->showName();//current Student class is stu2 ,current Person class is stu2_persion $stu1->showName();//current Student class is stu1 ,current Person class is stu2_persion //這說明了克隆以后,stu1和stu2對象person屬性里面仍然保存的是同一個對象的引用 //如果讓stu1和stu2對象person屬性不是同一個對象,只需要改寫Student類的clone,即將77行注釋取消掉即可 $stu3=clone $stu1; $stu3->setName('stu3'); $stu3->setPersonName('stu3_persion'); $stu3->showName();//current Student class is stu3 ,current Person class is stu3_persion $stu1->showName();//current Student class is stu1 ,current Person class is xiaowang
相關推薦:
jQuery中clone()函數實現表單中增加和減少輸入項
如何理解DOM拷貝clone()
javascript中clone克隆對象/函數代碼詳解
以上就是詳解PHP中引用以及clone的詳細內容,更多請關注php中文網其它相關文章!