Rumah > php教程 > php手册 > php __clone需要注意的问题

php __clone需要注意的问题

WBOY
Lepaskan: 2016-06-13 09:40:18
asal
1085 orang telah melayarinya

 

<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>
Salin selepas log masuk

当创建一个新副本($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>
Salin selepas log masuk
Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
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
Cadangan popular
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan