php destructor behaviour

前端 未结 5 1672
一个人的身影
一个人的身影 2020-12-16 00:23

im trying to understand php constructor and destructor behaviour. Everything goes as expected with the constructor but i am having trouble getting the destructor to fire imp

5条回答
  •  一个人的身影
    2020-12-16 01:10

    This is pretty easy to test.

    name = $name;
        }
    
        function __destruct() {
            echo "Destructing $this->name\n";
            //exit;
        }
    }
    
    echo "Start script\n";
    
    register_shutdown_function(function() {
        echo "Shutdown function\n";
        //exit
    });
    
    $a = new DestructTestDummy("Mr. Unset");
    $b = new DestructTestDummy("Terminator 1");
    $c = new DestructTestDummy("Terminator 2");
    
    echo "Before unset\n";
    unset($a);
    echo "After unset\n";
    
    
    echo "Before func\n";
    call_user_func(function() {
        $c = new DestructTestDummy("Mrs. Scopee");
    });
    echo "After func\n";
    
    $b->__destruct();
    
    exit("Exiting\n");
    

    In PHP 5.5.12 this prints:

    Start script
    Constructing Mr. Unset
    Constructing Terminator 1
    Constructing Terminator 2
    Before unset
    Destructing Mr. Unset
    After unset
    Before func
    Constructing Mrs. Scopee
    Destructing Mrs. Scopee
    After func
    Destructing Terminator 1
    Exiting
    Shutdown function
    Destructing Terminator 2
    Destructing Terminator 1
    

    So we can see that the destructor is called when we explicitly unset the object, when it goes out of scope, and when the script ends.

提交回复
热议问题