__destruct()
函数的“可见性”应该是公共的还是其他的?我正在试着为我的团队写一个标准文档,然后这个问题出现了。
发布于 2008-10-23 16:13:55
除了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
这可能是无害的,但却是不干净的。
但最重要的是:如果析构函数被声明为私有或受保护,则在垃圾回收器尝试释放对象的瞬间,运行时将抛出致命错误:
<?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的优秀示例!)
https://stackoverflow.com/questions/230245
复制相似问题