PHP object cloning clone keyword and __clone() method

巴扎黑
Release: 2016-11-12 09:18:24
Original
1322 people have browsed it


PHP object cloning clone keyword and __clone() method

clone keyword is used to clone an identical object, and __clone() method is used to override the original properties and methods.

Object cloning

Sometimes we need to use two or more identical objects in a project. If we use the new keyword to re-create the object and then assign the same attributes, it will be cumbersome and error-prone. PHP provides an object cloning function, which can completely clone an identical object based on an object. Moreover, after cloning, the two objects will not interfere with each other.

Use keyword clone to clone an object. Syntax:

$object2 = clone $object;

Example:

<?php
class Person {
    private $name;
    private $age;
    function __construct($name, $age) {
        $this->name=$name;
        $this->age=$age;
    }
    function say() {
        echo "我的名字叫:".$this->name."<br />";
echo "我的年龄是:".$this->age;
    }
}
$p1 = new Person("张三", 20);
$p2 = clone $p1;
$p2->say();
?>
Copy after login

Run the example, output:

My name is: Zhang San

My age is: 20

__clone()

If you want to To change the contents of the original object after cloning, you need to add a special __clone() method to the class to override the original attributes and methods. The __clone() method is only automatically called when the object is cloned.

Example:

<?php
class Person {
    private $name;
    private $age;
    function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
    function say() {
        echo "我的名字叫:".$this->name;
echo " 我的年龄是:".$this->age."<br />";
    }
    function __clone() {
        $this->name = "我是假的".$this->name;
        $this->age = 30;
    }
}
$p1 = new Person("张三", 20);
$p1->say();
$p2 = clone $p1;
$p2->say();
?>
Copy after login

Run the example, output:

My name is: Zhang San My age is: 20

My name is: I am the fake Zhang San My age is: 30


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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!