Home > php教程 > php手册 > 克隆

克隆

WBOY
Release: 2016-06-13 11:16:03
Original
1171 people have browsed it

 

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

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

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

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


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

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

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

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

function getName() file://获取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() . "
");
?>


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