Home >Backend Development >PHP Tutorial >'Clone Sheep' in php
Definition: Clone objectclone
, that is, copying a new and identical object from an existing object, but the two are not the same object.
1. Object cloning is achieved through the clone keyword, namely: clone
Object
;
<?php class Saler{ //属性 public $count; private $money; } //实例化 $s1 = new Saler(); $s1->count = 1; //克隆 $s2 = clone $s1; ?>
2. The cloned object and the original object have two memory addresses, so they are two different objects
<?php //接上述代码 $s2->count = 2; echo $s1->count; //1,没有变化 ?>
3. The object will be instantiated when it is instantiated Automatically call the existing constructor method __construct()
. Similarly, inside the class, PHP allows you to define a __clone()
method. After the object is cloned, the newly cloned The object will automatically call
<?php class Saler{ //属性 public $count; private $money; //克隆方法 public function __clone(){ var_dump($this); //编号为2,代表是克隆出来的对象 $this->count++; } } //实例化 $s1 = new Saler(); $s1->count = 1; //克隆 $s2 = clone $s1; ?>
4. If the object is not allowed to be cloned, you can privatize the __clone()
method (essentially, the object is not allowed to be cloned externally) )
<?php class Saler{ //属性 public $count; private $money; //私有化克隆方法 private function __clone(){} } //实例化 $s1 = new Saler(); $s1->count = 1; //克隆 $s2 = clone $s1; //致命错误:不允许对象在外部访问一个私有方法 ?>
Recommended: php video tutorial
The above is the detailed content of 'Clone Sheep' in php. For more information, please follow other related articles on the PHP Chinese website!