Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 implicitly. Ive done all the reading on php.net and related sites, but i cant find an answer to this question.

If i have a simple class, something like:

class test{

     public function __construct(){
          print "contructing<br>";
     }

     public function __destruct(){
          print "destroying<br>";
     }
}

and i call it with something like:

$t = new test;

it prints the constructor message. However, i'd expect that when the scripts ends and the page is rendered that the destructor should fire. Of course it doesnt.

If i call unset($t); when the scripts ends, of course the destructor fires, but is there a way to get it to fire implicitly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
929 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is pretty easy to test.

<?php

class DestructTestDummy {
    protected $name;

    function __construct($name) {
        echo "Constructing $name
";
        $this->name = $name;
    }

    function __destruct() {
        echo "Destructing $this->name
";
        //exit;
    }
}

echo "Start script
";

register_shutdown_function(function() {
    echo "Shutdown function
";
    //exit
});

$a = new DestructTestDummy("Mr. Unset");
$b = new DestructTestDummy("Terminator 1");
$c = new DestructTestDummy("Terminator 2");

echo "Before unset
";
unset($a);
echo "After unset
";


echo "Before func
";
call_user_func(function() {
    $c = new DestructTestDummy("Mrs. Scopee");
});
echo "After func
";

$b->__destruct();

exit("Exiting
");

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...