What makes __destruct twice called in such 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();

Usually we should get the following output: (Yes, I got this result on two 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 the release of CentOS 5.7 and PHP 5.2.17, I got the following:

    __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 is the __destruct function called twice here? Especially for the first time.

I think there can be something special in the configuration, any suggestion?

Thanks.

===================

PS: This problem is not caused by the "Singleton Design Pattern". The same problem appeared with the following code:

<?php
class A
{
    function __construct()
    {   
        echo "__construct\n";
    }

    function __destruct()
    {
        var_dump(debug_backtrace());
        echo "__destruct\n";
    }
}
$a = new A(); 
+2
source share
1 answer

Finally, I find the reason.

This could be a bug in PHP 5.2.x:

If a

zend.ze1_compatibility_mode = On 

"__destruct" , , .

: https://bugs.php.net/bug.php?id=29756

PHP 5.3 . (PHP 5.3 )

, :)

+5

All Articles