Rumah  >  Artikel  >  pembangunan bahagian belakang  >  php __clone需要注意的问题_PHP教程

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

WBOY
WBOYasal
2016-07-13 10:35:13747semak imbas

 

<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>

当创建一个新副本($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>

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; 当创建一个新...
Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn