Home  >  Article  >  Backend Development  >  php object copy

php object copy

伊谢尔伦
伊谢尔伦Original
2016-11-23 13:55:31952browse

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. . Object copying can be done via the clone keyword (this will call the object's __clone() method if possible). The __clone() method in an object cannot be called directly.

$copy_of_object = clone $object;

When the object is copied, PHP 5 will perform a shallow copy of all properties of the object. All reference properties will still be references to the original variables.

void __clone (void)

When the copy 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 necessary).

Copy an object

<?php
    class SubObject
    {
        static $instances = 0;
        public $instance;
        public function __construct() {
            $this->instance = ++self::$instances;
        }
        public function __clone() {
            $this->instance = ++self::$instances;
        }
    }
    class MyCloneable
    {
        public $object1;
        public $object2;
        function __clone()
        {
            // 强制复制一份this->object, 否则仍然指向同一个对象
            $this->object1 = clone $this->object1;
        }
    }
    $obj = new MyCloneable();
    $obj->object1 = new SubObject();
    $obj->object2 = new SubObject();
    $obj2 = clone $obj;
    print("Original Object:\n");
    print_r($obj);
    print("Cloned Object:\n");
    print_r($obj2);
?>

The above routine will output:

Original Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 1
        )
    [object2] => SubObject Object
        (
            [instance] => 2
        )
)
Cloned Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 3
        )
    [object2] => SubObject Object
        (
            [instance] => 2
        )
)


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
Previous article:php object comparisonNext article:php object comparison