Home  >  Article  >  Backend Development  >  Detailed explanation of __clone() method in PHP

Detailed explanation of __clone() method in PHP

藏色散人
藏色散人Original
2019-07-26 13:49:135625browse

__clone(), called when the object copy is completed

In most cases, we do not need to completely copy an object to obtain its properties. But there is one case where it is really needed: if you have a GTK window object that holds window-related resources. You may want to copy a new window, keeping all the same properties as the original window, but it must be a new object (because if it is not a new object, changes in one window will affect the other window).

There is another situation: if object A stores a reference to object B, when you copy object A, and you want the object used in it to be no longer object B but a copy of B, then you must Get a copy of object A.

Function:

Object copying can be accomplished through the clone keyword (this will call the object's __clone() method if possible). The __clone() method in an object cannot be called directly.

Syntax:

$copy_of_object = clone $object;

Note:

When the object is copied, PHP 5 will execute A shallow copy. All reference properties will still be references to the original variables.

When copying is completed, if the __clone() method is defined, the __clone() method in the newly created object (the object generated by copying) will be called and can be used to modify the value of the attribute (if if necessary).

Look at the code:

<?php
class Person
{
    public $sex;
    public $name;
    public $age;
    public function __construct($name="",  $age=25, $sex=&#39;男&#39;)
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }
    public function __clone()
    {
        echo __METHOD__."你正在克隆对象<br>";
    }
}
$person = new Person(&#39;小明&#39;); // 初始赋值
$person2 = clone $person;
var_dump(&#39;persion1:&#39;);
var_dump($person);
echo &#39;<br>&#39;;
var_dump(&#39;persion2:&#39;);
var_dump($person2);

Look at the result:

Person::__clone你正在克隆对象
string(9) "persion1:" object(Person)#1 (3) { ["sex"]=> string(3) "男" ["name"]=> string(6) "小明" ["age"]=> int(25) } 
string(9) "persion2:" object(Person)#2 (3) { ["sex"]=> string(3) "男" ["name"]=> string(6) "小明" ["age"]=> int(25) }

Cloning is successful.

The above is the detailed content of Detailed explanation of __clone() method in PHP. For more information, please follow other related articles on the PHP Chinese website!

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