Home > Backend Development > PHP Tutorial > Issues you need to pay attention to with php __clone_PHP Tutorial

Issues you need to pay attention to with php __clone_PHP Tutorial

WBOY
Release: 2016-07-13 10:35:13
Original
770 people have browsed it

<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>
Copy after login

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>
Copy after login

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; When creating a new...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template