可以在对象类中定义一个__clone()方法来调整对象的克隆行为。此方法的代码将在克隆操作期间执行。除了将所有现有对象成员复制到目标对象之外,还会执行__clone()方法指定的操作。下面修改Corporate_Drone类,增加以下方法:

function __clone() { 
 $this->tiecolor = "blue";
}

之后,创建一个新的Corporate_Drone对象,增加employeeid成员的值,克隆这个对象,然后输出一些数据,从而显示克隆对象的tiecolor确实是通过__clone()方法设置的。示例代码:

<"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 />";
"htmlcode">
drone1 employeeID: 12345
drone2 employeeID: 67890
drone2 tiecolor:

再来一个小例子:

<"水果";
 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 />"; 
 }
}

$apple = new Fruit();
$apple->setName("大苹果");
$apple->setColor("红色");
echo $apple->showColor();

$clone_apple = $apple;
$clone_apple->setName("小苹果");
$clone_apple->setColor("青色");

echo $clone_apple->showColor();
"htmlcode">
<"水果";
 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();
"htmlcode">
<"peter", 15, new Account(1000));
  $person->setId(1);
  $person2 = clone $person;
  
  $person2->account->balance = 250;
  
  var_dump($person, $person2);
  
 "codetitle">复制代码 代码如下:
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) } }

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com