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