gpt4 book ai didi

php - 对循环中持续存在的类的引用

转载 作者:可可西里 更新时间:2023-11-01 00:54:48 24 4
gpt4 key购买 nike

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

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

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

<?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;

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

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

你需要:

$list1[] = $instance;

关于php - 对循环中持续存在的类的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49689889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com