gpt4 book ai didi

php - __destruct PHP 的可见性

转载 作者:IT王子 更新时间:2023-10-29 00:02:13 25 4
gpt4 key购买 nike

__destruct() 函数的“可见性”应该是公开的还是其他?我正在尝试为我的团队编写标准文档,然后出现了这个问题。

最佳答案

除了 Mark Biek 的回答:

__destruct() 函数必须公开。否则,该函数将不会在脚本关闭时执行:

Warning: Call to protected MyChild1::__destruct() from context '' during shutdown ignored in Unknown on line 0
Warning: Call to private MyChild2::__destruct() from context '' during shutdown ignored in Unknown on line 0

这可能没有害处,但很不干净。

但最重要的是:如果析构函数被声明为私有(private)或 protected ,则运行时将在垃圾收集器尝试释放对象时抛出 fatal error :

<?php
class MyParent
{
private function __destruct()
{
echo 'Parent::__destruct';
}
}

class MyChild extends MyParent
{
private function __destruct()
{
echo 'Child::__destruct';
parent::__destruct();
}
}

$myChild = new MyChild();
$myChild = null;
$myChild = new MyChild();

?>

输出

Fatal error: Call to private MyChild::__destruct() from context '' in D:\www\scratchbook\destruct.php on line 20

(感谢 Mark Biek 提供的优秀示例!)

关于php - __destruct PHP 的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/230245/

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