Home > Article > Backend Development > Issues you need to pay attention to with php __clone_PHP Tutorial
<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>
When a new copy ($p2) is created, the reference saved in the new object ($p2) points to the same $account object referenced by $p1.
If you do not want the object properties to be shared after being copied, you can explicitly copy the object pointed to by in the __clone method
<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>