是什么使__destruct在如此简单的PHP代码中被两次调用? [英] What makes __destruct called twice in such a simple PHP code?
问题描述
<?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();
通常,我们应该得到以下输出:(是的。我在2个不同的PHP服务器中得到了这个结果5.2.10-2ubuntu6.10和PHP 5.3.1)
Normally, we should get following output: (Yes. I got this result in 2 different servers with PHP 5.2.10-2ubuntu6.10 and PHP 5.3.1)
__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的服务器上,我得到了:
But, on another server with CentOS release 5.7 and PHP 5.2.17, I got this :
__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在这里被两次调用?尤其是第一次。
Why does the function __destruct called twice here? Especially the first time.
我认为配置中可能有一些特殊之处,有什么建议吗?
I think there might be something special in the configuration, any suggestion?
谢谢
==================
==================
PS :此问题不是由单一设计模式引起的。相同的问题出现在以下代码中:
PS: This problem is not caused by "Singleton design pattern". Same issue appeared with following code :
<?php
class A
{
function __construct()
{
echo "__construct\n";
}
function __destruct()
{
var_dump(debug_backtrace());
echo "__destruct\n";
}
}
$a = new A();
推荐答案
最后我找到了原因。
这可能是PHP 5.2.x中的错误:
It might be a bug in PHP 5.2.x :
如果
zend.ze1_compatibility_mode = On
上,您会看到 __destruct 两次,当执行我在问题中提供的代码时。
then you can see "__destruct" twice when execute the code I provide in my question.
此问题在其他版本中也有报道: https://bugs.php.net/bug.php?id=29756
This issue has been reported in other versions : https://bugs.php.net/bug.php?id=29756
在我的测试中不影响PHP 5.3。 (PHP 5.3删除了此设置)
Not affect PHP 5.3 in my test. (PHP 5.3 removed this setting)
希望此答案对以后的某些人有用:)
Hope this answer will be helpful for some guys later :)
这篇关于是什么使__destruct在如此简单的PHP代码中被两次调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!