【问题标题】:Php: Difference of Array and Object when manipulate returned "Reference"Php:操作返回“参考”时数组和对象的差异
【发布时间】:2020-07-21 05:11:17
【问题描述】:

我有一个对象(二),其中包含一个对象(一)和一个数组:

class One {
    public $a;
}

class Two {
    public $object;
    public $array;

    public function __construct() {
        $this->object = new One();
        $this->array = [];
    }

    function getObject() {
        return $this->object;
    }

    function getArray() {
        return $this->array;
    }
}

为什么我可以操作返回的对象,却不能操作返回的数组:

$two = new Two();
$two->getObject()->a = 'a';
$two->getArray()[] = 'b'; // Does not work!
$two->array[] = 'c';

var_dump($two);

结果(数组中缺少b):

//    class test\Two (2) {
//      protected $object =>
//        class test\One (1) { public $a => string(1) "a" }
//      protected $array => array(1) { [0] => string(1) "c" }
//    }

有什么不同,因为我认为返回了对数组本身的引用的副本,而不是它的元素。

感谢您的解释! ;D

【问题讨论】:

  • “不起作用”是否有任何错误信息?
  • @Nico:不,但它不会被分配,正如您在转储字符串中看到的那样。
  • 那么,是什么让您认为首先返回了引用?
  • 对象是通过引用返回的,而数组不是。

标签: php


【解决方案1】:

默认情况下,传递或返回一个数组会生成一个副本。你需要return a reference

    function &getArray() {
        return $this->array;
    }

顺便说一句,您需要将$array 声明为public,以便您可以在课堂外访问$two->array

【讨论】:

  • 感谢您的回复,我已经知道我必须返回一个引用,因此我不明白是什么让返回的数组与对象不同。 ;D(也将 $array 更改为 public Thx)
【解决方案2】:

传递/返回对象的类引用行为是由 object 类型的变量真正持有的结果。对象本身不存在于任何变量中 - 仅存在于内存中的某些空间中,您传递的实际上是一个链接/标识符(或简化的指针),它允许您调用对象的方法和(公共)属性(一种中间人)。默认情况下,对象(不是真正的对象,而是它们的代表)以与数组或任何其他变量相同的方式传递 - 按值(我跳过了一些底层优化,如数组的 写入时复制 例如)。

因此,重新分配对象变量和通过引用传递的变量之间的行为差​​异 - 后者将更改引用(及其原始变量)指向的内存,前者将覆盖对象的“链接”,而其他标识符该对象仍将保持相同的值。

对象也可以通过引用传递,但同样因为它不是真正的对象,所以除了调用或断开链接本身之外,你不能对它做任何事情——这次是针对引用者和引用变量。

【讨论】:

    【解决方案3】:

    您需要在 Two 类中将数组作为引用返回

    class One {
        public $a;
    }
    
    class Two {
        protected $object;
        protected $array;
    
        public function __construct() {
            $this->object = new One();
            $this->array = [];
        }
    
        function getObject() {
            return $this->object;
        }
    
        function &getArray() { // Here you return as reference
            return $this->array;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多