Learning how to use clone in 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"
"; - $person = new Person( "bob", 44 );
- $person->setId( 343 );
- $person2 = clone $person;
- print_r( $person );
- print_r( $person2 );
- print "
";
- ?>
Demo code 2:
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-> setId (343 );
- $ Person2 = clone $ person;
// Give $ person some money
- $ Person-> account-> balance + = 10;
- // $ Person2 sees the credit too
- Print $ person2-> account-> balance;
// Output:
- // 210
- ?>
Official documents: http://cn2.php.net/__clone |