gpt4 book ai didi

PHP 取消设置类对象数组中的类对象调用所有类对象的 destruct?

转载 作者:搜寻专家 更新时间:2023-10-31 21:14:18 26 4
gpt4 key购买 nike

我有一组存储在 PHP 数组中的客户端类对象。有时我需要 unset() 数组中的其中一个对象,但我不想担心显式关闭套接字连接。我希望 __destruct() 为我做这件事。

class A{

private $id;

public function __construct( $id ){
$this->id = $id;
}

public function __destruct(){
echo "Calling destruct on " . $this->id . ".\n";
}

}

$array = array();

for($i=0;$i<5;$i++){
$array[$i] = new A($i);
}

unset($array[3]);

print_r($array);

对于我们要销毁的元素,析构函数应该被触发。但是即使元素没有被销毁,数组中的每个其他析构函数也会被调用。为什么?

Calling destruct on 3.
Array
(
[0] => A Object
(
[id:A:private] => 0
)

[1] => A Object
(
[id:A:private] => 1
)

[2] => A Object
(
[id:A:private] => 2
)

[4] => A Object
(
[id:A:private] => 4
)

)
Calling destruct on 0.
Calling destruct on 1.
Calling destruct on 2.
Calling destruct on 4.

为什么会发生这种情况,我有哪些替代方案?

最佳答案

如果 $array 超出范围,则其余对象也将被销毁。

这似乎正在发生。您会看到您的 destruct 跟踪消息,然后是您的 print_r() 输出,然后是其余的对象 destruct。

关于PHP 取消设置类对象数组中的类对象调用所有类对象的 destruct?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12487256/

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