/* + ------------------------------------------------------------------------------- + | = Read this article for haohappy <core PHP programming> | = Notes in the classes and objects chapter | = Translation-oriented + personal experiences | = Do not repost it to avoid unnecessary troubles. Thank you. | = Thank you for your criticism and hope to make progress together with all PHP fans! + ------------------------------------------------------------------------------- + */Section 5-clone The object model in PhP5 calls an object through reference, but sometimes you may want to create a copy of the object and expect 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, the front has two underscores. By default, the _ clone method is used to create an object with the same attributes and methods as the original object. if you want to change the default content during cloning, overwrite (attribute or method) in _ clone ). The clone method can have no parameters, but it also contains the this and that pointers (that points to the Copied object ). if you choose to clone yourself, you must be careful to copy any information contained in your object, from that to this. if you use _ clone to copy. PHP will not perform any implicit replication, The following shows an example of automatic objects using sequence numbers: <? 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 () // obtain the ID Attribute Value { Return ($ this-> ID ); } Function getname () // obtain 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> "); ?> |