ArticleDirectory
Clone usage in PHP
Official documents: http://cn2.php.net/__clone
In most cases, we do not need to completely copy an object to obtain its attributes. However, you need to: If you have a GTK window object, the object holds window-related resources. You may want to copy a new window to keep all attributes the same as the original window, but it must be a new object (because if it is not a new object, changes in one window will affect the other window ). Another case is: If object A contains the reference of object B, when you copy object A, you want to use the object instead of object B but a copy of object B, then you must get a copy of object.
Object replication can be completed by using the clone keyword (if possible, the _ clone () method of the object will be called ). The _ clone () method in the object cannot be called directly.
Demo 1
<? PHP Class Person { Private $ Name ; Private $ Age ; Private $ ID ; Function _ Construct ( $ Name , $ Age ){ $ This -> Name = $ Name ; $ This -> Age = $ Age ;} Function Setid ( $ ID ){ $ This -> Id = $ ID ;} Function _ Clone (){ $ This -> Id = 0 ;}} Print "<PRE>" ; $ Person = New Person ("Bob", 44 ); $ Person -& Gt; setid (343 ); $ Person2 = Clone $ Person ; Print_r ( $ Person ); Print_r ( $ Person2 ); Print "</PRE>" ; ?>
DEMO 2
<? PHP Class Account { Public $ Balance ; Function _ Construct ( $ Balance ){ $ This -> Balance = $ Balance ;}} Class Person { Private $ Name ; Private $ Age ; Private $ ID ; Public $ Account ; Function _ Construct ( $ Name , $ Age , Account $ Account ){ $ This -> Name = $ Name ; $ This -> Age = $ Age ; $ This -> Account = $ Account ;} Function Setid ( $ ID ){ $ This -> Id = $ ID ;} Function _ Clone (){ $ This -> Id = 0 ;}} $ Person = New Person ("Bob", 44, New Account (200 )); $ Person -& Gt; setid (343 ); $ Person2 = Clone $ Person ; // Give $ person some money $ Person -> Account-> balance + = 10 ; // $ Person2 sees the credit too Print $ Person2 -> Account-> Balance; // Output: // 210 ?>