Section 5 - Cloning - Classes and Objects in PHP5 [5]

zhaozj2021-02-16  49

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: 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 ()."
");?>

转载请注明原文地址:https://www.9cbs.com/read-21571.html

New Post(0)