Maison > développement back-end > tutoriel php > php __clone需要注意的问题_PHP教程

php __clone需要注意的问题_PHP教程

WBOY
Libérer: 2016-07-13 10:35:13
original
769 Les gens l'ont consulté

 

<span class</span><span  Account{
    </span><span public</span> <span $balance</span><span ;
   </span><span function</span> __construct(<span $balance</span><span ){
       </span><span $this</span>->balance=<span $balance</span><span ;
   }
}

</span><span class</span><span  Person{
  </span><span private</span> <span $name</span><span ;
  </span><span private</span> <span $age</span><span ;
  </span><span private</span> <span $id</span><span ;
  </span><span public</span> <span $account</span><span ;
  </span><span function</span> __construct(<span $name</span>,<span $age</span>,<span $account</span><span ){
      </span><span $this</span>->name=<span $name</span><span ;
      </span><span $this</span>->age=<span $age</span><span ;
      </span><span $this</span>->account=<span $account</span><span ;
  }
  </span><span function</span> setId(<span $id</span><span ){
    </span><span $this</span>->id=<span $id</span><span ;
  }
  </span><span function</span><span  __clone(){
   </span><span $this</span>->id=0<span ;

  }
}
</span><span $p1</span>=<span new</span> Person('tom', 33, <span new</span> Account(200<span ));
</span><span $p1</span>->setId(4<span );

</span><span $p2</span>=<span clone</span> <span $p1</span><span ;
</span><span //</span><span 给$p1充500 </span>
<span $p1</span>->account->balance+=500<span ;
</span><span //</span><span 结果$p2也得到了这笔钱</span>
<span print</span> <span $p2</span>->account->balance; <span //</span><span 700</span>
Copier après la connexion

当创建一个新副本($p2)时,新对象($p2)的中所保存的引用指向的是$p1所引用的同一个$account对象.

如果不想对象属性在被复制之后被共享,可以显式地在__clone方法中复制指向的对象

<span function</span><span  __clone(){
   </span><span $this</span>->id=0<span ;
   </span><span $this</span>->account=<span clone</span> <span $this</span>-><span account;

  }</span>
Copier après la connexion

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/745143.htmlTechArticle__construct( -balance= __construct( , , -name= -age= -account= setId( -id= -id=0 = Person('tom', 33, Account(200 -setId(4 = -account-balance+=500 -account-balance; 当创建一个新...
Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal