ホームページ  >  記事  >  バックエンド開発  >  PHP でのクローンの使用方法を学ぶ

PHP でのクローンの使用方法を学ぶ

WBOY
WBOYオリジナル
2016-07-25 09:07:44934ブラウズ
  1. class person {

  2. private $name;
  3. プライベート$年齢;
  4. プライベート $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 "
    "; <li>$person = 新しい Person( "bob", 44 );<li>$person->setId( 343 );</li>
    <li>$person2 = クローン $person;</li>
    <li>print_r( $person );</li>
    <li>print_r( $person2 );</li>
    <li>print " 
    ";
  17. ?>

复制代码

演示代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. }< ;/p>
  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 = クローン $person;

  27. // $person にお金をあげます

  28. $person->account->残高 += 10;
  29. // $person2 にもクレジットが表示されます
  30. print $person2->account->balance;

  31. // Output:

  32. // 210
  33. ?>

复制番号

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



声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。