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;
    
      }
  • 相关阅读:
    Sizzle之tokenize
    直转字符串为数组
    Sizzle前奏
    (242-528)
    (177-240)
    (92-176)
    (63~91)
    一些变量(39~62)
    mysql导入导出sql文件
    vim编辑器的一些操作
  • 原文地址:https://www.cnblogs.com/HKUI/p/3619444.html
Copyright © 2011-2022 走看看