Home  >  Article  >  Backend Development  >  In-depth exploration of PHP 5.0 object model - object copy_PHP tutorial

In-depth exploration of PHP 5.0 object model - object copy_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:53:05695browse

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 the default content when cloning, 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 choose to clone yourself, you need to be careful to copy any information you want your object to contain, from that to this. PHP will not perform any implicit copying if you use __clone to copy. The following shows an example using a series ordinal. Example of automating objects:

Copy code The code is as follows:

class ObjectTracker //Object Tracker
{
private static $nextSerial = 0;
private $id;
private $name;

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

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

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

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

$ot = new ObjectTracker("Zeev's Object");  
$ot2 = clone$ot;  

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

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


http://www.bkjia.com/PHPjc/318832.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/318832.htmlTechArticleBy default, using the __clone method will create an object with the same properties and methods as the original object. If you want To change the default content when cloning, you have to override (properties or methods...
in __clone
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