zoukankan      html  css  js  c++  java
  • php __clone需要注意的问题

      当一个对象的属性是另外一个对象时,当有一个对象复制该对象时,当复制到这个属性(一个对象)时,只复制这个属性(对象)的引用,而不复制引用的对象。

    class Account{
        public $balance;
       function __construct($balance){
           $this->balance=$balance;
       }
    }
    
    class Person{
      private $name;
      private $age;
      private $id;
      public $account;
      function __construct($name,$age,$account){
          $this->name=$name;
          $this->age=$age;
          $this->account=$account;
      }
      function setId($id){
        $this->id=$id;
      }
      function __clone(){
       $this->id=0;
    
      }
    }
    $p1=new Person('tom', 33, new Account(200));
    $p1->setId(4);
    
    $p2=clone $p1;
    //给$p1充500 
    $p1->account->balance+=500;
    //结果$p2也得到了这笔钱
    print $p2->account->balance; //700

    当创建一个新副本($p2)时,新对象($p2)的中所保存的引用指向的是$p1所引用的同一个$account对象.

    如果不想对象属性在被复制之后被共享,可以显式地在__clone方法中复制指向的对象

    function __clone(){
       $this->id=0;
       $this->account=clone $this->account;
    
      }
  • 相关阅读:
    求斐波那契数列的第n项
    八大经典排序算法
    [BZOJ 3083] 遥远的国度
    [BZOJ 3306] 树
    [SCOI 2010] 序列操作
    [AHOI 2013] 差异
    [USACO2006 DEC] Milk Patterns
    [JSOI 2007] 字符加密
    [BZOJ 2588] Count on a tree
    [NOIP 2018 Day1] 简要题解
  • 原文地址:https://www.cnblogs.com/HKUI/p/3619444.html
Copyright © 2011-2022 走看看