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

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

oop - php destructor behaviour

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...