问题
<?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();
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
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
Why does the function __destruct called twice here? Especially the first time.
I think there might be something special in the configuration, any suggestion?
Thanks.
==================
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();
回答1:
Finally I find the reason.
It might be a bug in PHP 5.2.x :
If
zend.ze1_compatibility_mode = On
then you can see "__destruct" twice when execute the code I provide in my question.
This issue has been reported in other versions : https://bugs.php.net/bug.php?id=29756
Not affect PHP 5.3 in my test. (PHP 5.3 removed this setting)
Hope this answer will be helpful for some guys later :)
来源:https://stackoverflow.com/questions/8455103/what-makes-destruct-called-twice-in-such-a-simple-php-code