SoFunction
Updated on 2025-04-04

Section 5 - Cloning

/*
+-------------------------------------------------------------------------------+
| = This article is read by Haohappy<<Core PHP Programming>>
| =Notes from the chapter Classes and Objects
| = Translation as the main + personal experience
| = To avoid unnecessary troubles that may occur, please do not reprint, thank you
| = Criticism and correction are welcome, and I hope to make progress with all PHP enthusiasts!
| = PHP5 Research Center:/haohappy2004
+-------------------------------------------------------------------------------+
*/

Section 5 - Cloning

The object model in PHP5 calls objects through references, but sometimes you may want to create a copy of the object and hope that the change of the original object will not affect the copy. For this purpose, PHP defines a special method called __clone. Like __construct and __destruct, there are two underscores in front.

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 during cloning, you need to overwrite (properties or methods) in __clone.

The cloned 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 must 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,

Here is an example of using series ordinal numbers to automate objects:

Copy the codeThe code is as follows:
<?php  
class ObjectTracker //Object Tracker
   {  
       private static $nextSerial = 0;  
       private $id;  
       private $name;  

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

function __clone()  //Clone
       {  
           $this->name = "Clone of $that->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 = $ot->__clone();  

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

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