Home > php教程 > php手册 > body text

第五节--克隆 -- Classes and Objects in PHP5 [5]

WBOY
Release: 2016-06-13 11:21:13
Original
918 people have browsed it

第五节--克隆
PHP5中的对象模型通过引用来调用对象, 但有时你可能想建立一个对象的副本,并希望原来的对象的改变不影响到副本 . 为了这样的目的,PHP定义了一个特殊的方法,称为__clone. 像__construct和__destruct一样,前面有两个下划线.
默认地,用__clone方法将建立一个与原对象拥有相同属性和方法的对象. 如果你想在克隆时改变默认的内容,你要在__clone中覆写(属性或方法).
克隆的方法可以没有参数,但它同时包含this和that指针(that指向被复制的对象). 如果你选择克隆自己,你要小心复制任何你要你的对象包含的信息,从that到this. 如果你用__clone来复制. PHP不会执行任何隐性的复制,
下面显示了一个用系列序数来自动化对象的例子:
绿色c hinaip ower. com7AT0x
     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);
         }

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!