Home > Backend Development > PHP Tutorial > 'Clone Sheep' in php

'Clone Sheep' in php

autoload
Release: 2023-04-09 20:02:02
Original
2072 people have browsed it

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;
?>
Copy after login

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,没有变化
?>
Copy after login

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;
?>
Copy after login

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;			//致命错误:不允许对象在外部访问一个私有方法
?>
Copy after login

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!

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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template