本篇文章主要介紹PHP中的__clone()怎麼調用,感興趣的朋友參考下,希望對大家有所協助。
可以在對象類中定義一個__clone()方法來調整對象的複製行為。此方法的代碼將在複製操作期間執行。除了將所有現有對象成員複製到目標對象之外,還會執行__clone()方法指定的操作。下面修改Corporate_Drone類,增加以下方法:
function __clone() { $this->tiecolor = "blue";}
之後,建立一個新的Corporate_Drone對象,增加employeeid成員的值,複製這個對象,然後輸出一些資料,從而顯示複製對象的tiecolor確實是通過__clone()方法設定的。範例程式碼:
<?php // Create new corporatedrone object $drone1 = new corporatedrone(); // Set the $drone1 employeeid member $drone1->setEmployeeID("12345"); // Clone the $drone1 object $drone2 = clone $drone1; // Set the $drone2 employeeid member $drone2->setEmployeeID("67890"); // Output the $drone1 and $drone2 employeeid members echo "drone1 employeeID: ".$drone1->getEmployeeID()."<br />"; echo "drone2 employeeID: ".$drone2->getEmployeeID()."<br />"; echo "drone2 tiecolor: ".$drone2->getTiecolor()."<br />";?>
程式運行結果
drone1 employeeID: 12345drone2 employeeID: 67890drone2 tiecolor:
上面只是將一個類賦值給另一個類,所以此時記憶體中仍是一個對象。
<?phpclass Fruit { private $name = "水果"; private $color = "顏色"; public function setName($name){ $this->name = $name; } public function setColor($color){ $this->color = $color; } function showColor(){ return $this->color.'的'.$this->name."<br />"; } function __destruct(){ echo "被吃掉了(對象被回收) <br />"; } function __clone(){ $this->name = "複製水果"; }}$apple = new Fruit();$apple->setName("大蘋果");$apple->setColor("紅色");echo $apple->showColor();$clone_apple = clone $apple;$clone_apple->setColor("青色");echo $clone_apple->showColor();?>
clone方法複製出了一個新的類,所以此時記憶體中有兩個對象。
php的__clone()方法對一個對象執行個體進行的淺複製,對象內的基本數實值型別進行的是傳值複製,而對象內的對象型成員變數,如果不重寫__clone方法,顯式的clone這個對象成員變數的話,這個成員變數就是傳引用複製,而不是產生一個新的對象.如下面一個例子的第28行注釋所說
<?php class Account { public $balance; public function __construct($balance) { $this->balance = $balance; } } class Person { private $id; private $name; private $age; public $account; public function __construct($name, $age, Account $account) { $this->name = $name; $this->age = $age; $this->account = $account; } public function setId($id) { $this->id = $id; } public function __clone() { #複製方法,可在裡面定義再clone是進行的操作 $this->id = 0; $this->account = clone $this->account; #不加這一句,account在clone是會只被複製引用,其中一個account的balance被修改另一個也同樣會被修改 } } $person = new Person("peter", 15, new Account(1000)); $person->setId(1); $person2 = clone $person; $person2->account->balance = 250; var_dump($person, $person2); ?>
輸出:
代碼如下:
object(Person)#1 (4) { ["id":"Person":private]=> int(1) ["name":"Person":private]=> string(5) "peter" ["age":"Person":private]=> int(15) ["account"]=> object(Account)#2 (1) { ["balance"]=> int(1000) } } object(Person)#3 (4) { ["id":"Person":private]=> int(0) ["name":"Person":private]=> string(5) "peter" ["age":"Person":private]=> int(15) ["account"]=> object(Account)#4 (1) { ["balance"]=> int(250) } }
總結:以上就是本篇文的全部內容,希望能對大家的學習有所協助。