<?php
class A
{
static private $_instance = null;
static public function Init()
{
self::$_instance = new A();
}
function __construct()
{
echo "__construct\n";
}
function __destruct()
{
var_dump(debug_backtrace());
echo "__destruct\n";
}
}
$a = A::Init();
通常,我们应该得到以下输出:(是的。我使用PHP 5.2.10-2ubuntu6.10和PHP 5.3.1在2个不同的服务器中得到了这个结果)
__construct
array(1) {
[0]=>
array(5) {
["function"]=>
string(10) "__destruct"
["class"]=>
string(1) "A"
["object"]=>
object(A)#1 (0) {
}
["type"]=>
string(2) "->"
["args"]=>
array(0) {
}
}
}
__destruct
但是,在使用CentOS版本5.7和PHP 5.2.17的另一台服务器上,我得到了这个:
__construct
array(2) {
[0]=>
array(7) {
["file"]=>
string(10) "/tmp/1.php"
["line"]=>
int(7)
["function"]=>
string(10) "__destruct"
["class"]=>
string(1) "A"
["object"]=>
object(A)#1 (0) {
}
["type"]=>
string(2) "->"
["args"]=>
array(0) {
}
}
[1]=>
array(6) {
["file"]=>
string(10) "/tmp/1.php"
["line"]=>
int(21)
["function"]=>
string(4) "Init"
["class"]=>
string(1) "A"
["type"]=>
string(2) "::"
["args"]=>
array(0) {
}
}
__destruct
array(1) {
[0]=>
array(5) {
["function"]=>
string(10) "__destruct"
["class"]=>
string(1) "A"
["object"]=>
object(A)#2 (0) {
}
["type"]=>
string(2) "->"
["args"]=>
array(0) {
}
}
}
__destruct
为什么__destruct函数在这里调用了两次?特别是第一次。
我认为配置中可能有一些特别的东西,有什么建议吗?
感谢。
==================
PS:此问题不是由“Singleton设计模式”引起的。以下代码中出现了同样的问题:
<?php
class A
{
function __construct()
{
echo "__construct\n";
}
function __destruct()
{
var_dump(debug_backtrace());
echo "__destruct\n";
}
}
$a = new A();
答案 0 :(得分:5)
最后我找到了原因。
它可能是PHP 5.2.x中的错误:
如果
zend.ze1_compatibility_mode = On
然后在执行我在问题中提供的代码时,您可以看到“__destruct”两次。
其他版本已报告此问题:https://bugs.php.net/bug.php?id=29756
在我的测试中不影响PHP 5.3。 (PHP 5.3删除了此设置)
希望这个答案对以后的某些人有用:)