Home >Backend Development >PHP Tutorial > php的对象clone施用

php的对象clone施用

WBOY
WBOYOriginal
2016-06-13 13:03:40867browse

php的对象clone使用

1。?

? ? PHP5中定义了一个__clone()将建立一个与原来的对象拥有相同属性和方法的对象。如果想在克隆后改变原对象的内容,需要在__clone()中重写原本的属性和方法。

?

????? __clone()可以没有参数,它自动包含$this和$that两个指针。

$this 指向复本

$that指向原本

?

2。

如果是类里声明了新类

class ConcretePrototype{
?? ?public function __construct() {
?? ??? ?$this->id = 1;
?? ??? ?$this->obj = new StdClass();
?? ??? ?$this->obj->name = 'dashu';
?? ?}
?? ?
?? ?public function myclone() {
?? ??? ?return clone $this;
?? ?}
???

????// 没有这个,$obj 就是引用,有了才是互相独立的两个,亲自试一下看看
????private function __clone() {
?? ??? ?$this->obj = clone $this->obj;
?? ?}
}

$p = new ConcretePrototype();
$q = $p->myclone();
var_dump($p, $q);
$q->id = 2;
//改变$q的obj的属性,$p的相应属性不变化
$q->obj->name = 'xiayi';
var_dump($p, $q);

?

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