Home  >  Article  >  php教程  >  第五节--克隆

第五节--克隆

WBOY
WBOYOriginal
2016-06-13 12:37:03926browse

/*
+-------------------------------------------------------------------------------+
| = 本文为Haohappy读> 
| = 中Classes and Objects一章的笔记 
| = 翻译为主+个人心得 
| = 为避免可能发生的不必要的麻烦请勿转载,谢谢 
| = 欢迎批评指正,希望和所有PHP爱好者共同进步! 
| = PHP5研究中心: http://blog.csdn.net/haohappy2004
+-------------------------------------------------------------------------------+
*/

第五节--克隆

PHP5中的对象模型通过引用来调用对象, 但有时你可能想建立一个对象的副本,并希望原来的对象的改变不影响到副本 . 为了这样的目的,PHP定义了一个特殊的方法,称为__clone. 像__construct和__destruct一样,前面有两个下划线.

默认地,用__clone方法将建立一个与原对象拥有相同属性和方法的对象. 如果你想在克隆时改变默认的内容,你要在__clone中覆写(属性或方法).

克隆的方法可以没有参数,但它同时包含this和that指针(that指向被复制的对象). 如果你选择克隆自己,你要小心复制任何你要你的对象包含的信息,从that到this. 如果你用__clone来复制. PHP不会执行任何隐性的复制, 

下面显示了一个用系列序数来自动化对象的例子:

复制代码 代码如下:

   class ObjectTracker //对象跟踪器  
   {  
       private static $nextSerial = 0;  
       private $id;  
       private $name;  

       function __construct($name) //构造函数  
       {  
           $this->name = $name;  
           $this->id = ++self::$nextSerial;  
       }  

       function __clone()  //克隆  
       {  
           $this->name = "Clone of $that->name";  
           $this->id = ++self::$nextSerial;  
       }  

       function getId() //获取id属性的值  
       {  
           return($this->id);  
       }  

       function getName() //获取name属性的值  
       {  
           return($this->name);  
       }  
   }  

   $ot = new ObjectTracker("Zeev's Object");  
   $ot2 = $ot->__clone();  

   //输出: 1 Zeev's Object  
   print($ot->getId() . " " . $ot->getName() . "
");  

   //输出: 2 Clone of Zeev's Object  
   print($ot2->getId() . " " . $ot2->getName() . "
");  
?>  

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn