Heim  >  Artikel  >  Backend-Entwicklung  >  学习php中clone的使用

学习php中clone的使用

WBOY
WBOYOriginal
2016-07-25 09:07:44935Durchsuche
  1. class Person {

  2. private $name;
  3. private $age;
  4. private $id;
  5. function __construct( $name, $age ) {

  6. $this->name = $name;
  7. $this->age = $age;
  8. }
  9. function setId( $id ) {

  10. $this->id = $id;
  11. }
  12. function __clone() {
  13. $this->id = 0;
  14. }
  15. }
  16. print "
    ";
  17. $person = new Person( "bob", 44 );
  18. $person->setId( 343 );
  19. $person2 = clone $person;
  20. print_r( $person );
  21. print_r( $person2 );
  22. print "";
  23. ?>
复制代码

演示代码2:

  1. class Account {

  2. public $balance;
  3. function __construct( $balance ) {
  4. $this->balance = $balance;
  5. }
  6. }
  7. class Person {

  8. private $name;
  9. private $age;
  10. private $id;
  11. public $account;
  12. function __construct( $name, $age, Account $account ) {

  13. $this->name = $name;
  14. $this->age = $age;
  15. $this->account = $account;
  16. }
  17. function setId( $id ) {

  18. $this->id = $id;
  19. }
  20. function __clone() {

  21. $this->id = 0;
  22. }
  23. }
  24. $person = new Person( "bob", 44, new Account( 200 ) );

  25. $person->setId( 343 );
  26. $person2 = clone $person;
  27. // give $person some money

  28. $person->account->balance += 10;
  29. // $person2 sees the credit too
  30. print $person2->account->balance;
  31. // output:

  32. // 210
  33. ?>
复制代码

官方文档:http://cn2.php.net/__clone



Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn