【问题标题】:Reference to class persisting in loop引用持续循环的类
【发布时间】:2018-09-16 07:27:22
【问题描述】:

我通过循环创建了一堆基本类的实例。 每次迭代,我都会将实例添加(通过引用,而不是复制)到数组中。

为什么在循环之后,数组中的每个引用都指向最后创建的实例?

执行取消设置似乎可以解决问题,但我认为这不是理想的,并且可能会从内存中取消设置底层实例。

<?php
//foobars remembers something
class FOOBAR{
    public $val;
    public function __construct(&$input){
        $this->val = $input;
    }
};

//after creating foobars, pass them to a list
$list1 = [];
for($i=1; $i<=5; $i++){
    //create an instance of foobar
    $random = rand(1, 10);
    $instance = new FOOBAR($random);
    $list1[] = &$instance;

    // Using unset (below) fixes it?
    //unset($instance);
}

//show what our foobars remembered
var_dump(json_encode($list1));
?>

【问题讨论】:

  • $list1[] = $instance; 会工作。但不确定为什么它不适用于&amp;

标签: php loops class memory php-7.1


【解决方案1】:

这是你的问题:

$list1[] = &$instance;

您的数组中的项目包含对$instance 变量的引用。一旦您更改该变量 - 在您的情况下的循环的下一次迭代中 - 数组中的项目引用新创建的项目。

所以在循环之后,数组中的所有条目都会引用您创建的最后一个对象。

你需要:

$list1[] = $instance;

【讨论】:

  • 我原以为 $instance 持有对通过“new”创建的类的引用。我没有意识到 $instance 本身正在存储实例。可能我希望“新”和类的工作类似于 C/C++ !干杯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多