Section 5 - Cloning - Classes and Objects in PHP5 [5]
Author: Leon Atkinson translation: Haohappy Source: Beyond the PHP / * ------------------------------------ ------------------------------------------ | = This article is HaohappY << CORE PHP Programming >> | = Classes and Objects Chapter Note | = Translate Main Personal Experience | = To avoid unnecessary troubles, please do not reprint, thank you | = Welcome criticism, hope and all PHP enthusiasts progress together! ----------------------------------------- ---------------------------------- * / Section 5 - Clone PHP5 Object Model Call the object by reference, but sometimes you may want to build a copy of an object, and hope that the original object change does not affect the copy. For this purpose, PHP defines a special method, called __clone. Like __construct Like __destruct, there are two underscores. By default, the __clone method will create an object that has the same properties and methods with the original object. If you want to change the default content while you want to change the default content, you have to overdone in __clone Write (attributes or methods). Clones can have no parameters, but it also contains this and That pointer (That pointing to the copied object). If you choose to clone yourself, you have to copy any information you want your object. From That to this. If you use __clone to copy. PHP does not execute any hidden copy, the following shows an example of a series of sequences to vibrant objects: 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 () // Take the value of the id attribute {RETURN ($ this-> id);} Function getName () // Get the value of the Name property {Return ($ this-> name);}} $ = 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 ()."
");?>