Home > Backend Development > PHP Tutorial > Section 5 Cloning [5]_PHP Tutorial

Section 5 Cloning [5]_PHP Tutorial

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-07-21 16:10:52
Original
935 people have browsed it


The object model in PHP5 calls objects by reference, but sometimes you may want to create a copy of the object and hope that changes to the original object will not affect the copy. For this purpose, PHP defines a special method called _ _clone. Like __construct and __destruct, preceded by two underscores.

By default, using the __clone method will create an object with the same properties and methods as the original object. If you want to change it during cloning The default content, you have to override (properties or methods) in __clone.

The clone method can have no parameters, but it contains both this and that pointers (that points to the copied object). If you When choosing to clone yourself, you need to be careful to copy any information you want your object to contain, from that to this. If you use __clone to copy. PHP will not perform any implicit copying,

shown below An example of using serial ordinal numbers to automate objects: class ObjectTracker file://Object Tracker
{
private static $nextSerial = 0;
private $id;
private $name;

function __construct($name) file://constructor
{
$this->name = $name;
$this->id = ++self::$nextSerial;
}

function __clone() file://clone
{
$this->name = "Clone of $that->name";
$this->id = ++self::$nextSerial;
}

function getId() file://Get the value of the id attribute
{
return($this->id);
}

function getName() file://Get the value of the name attribute
{
return($this->name);
}
}

$ot = new ObjectTracker("Zeev's Object");
$ot2 = $ot->__clone();

//Output: 1 Zeev's Object
print($ot ->getId() . " " . $ot->getName() . "
");

//Output: 2 Clone of Zeev's Object
print($ot2- >getId() . " " . $ot2->getName() . "
");
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/314114.htmlTechArticleThe object model in PHP5 calls objects by reference, but sometimes you may want to make a copy of the object and wish Changes to the original object do not affect the copy. For this purpose, PHP determines...
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