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
499 views
in Technique[技术] by (71.8m points)

image processing - PHP: destructor vs register_shutdown_function

I have a PHP class that creates a PNG image on the fly and sends it to browser. PHP manual says that I need to make sure that imagedestroy function is called at end to release the memory. Now, if I weren't using a class, I would have some code like this:

function shutdown_func() 
{
    global $img;
    if ($img)
        imagedestroy($img);
}
register_shutdown_function("shutdown_func");

However, I believe that appropriate place for my class would be to place a call to imagedestroy in class' destructor.

I failed to find out if destructors get called the same way shutdown functions does? For example, if execution stops when user presses the STOP button in browser.

Note: whatever you write in your answer, please point to some article or manual page (URL) that supports it.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

I just tested with Apache, PHP being used as Apache module. I created an endless loop like this:

<?php
class X
{
    function __destruct()
    {
        $fp = fopen("/var/www/htdocs/dtor.txt", "w+");
        fputs($fp, "Destroyed
");
        fclose($fp);
    }
};

$obj = new X();
while (true) {
    // do nothing
}
?>

Here's what I found out:

  • pressing STOP button in Firefox does not stop this script
  • If I shut down Apache, destructor does not get called
  • It stops when it reaches PHP max_execution_time and destuctor does not get called

However, doing this:

<?php
function shutdown_func() {
    $fp = fopen("/var/www/htdocs/dtor.txt", "w+");
    fputs($fp, "Destroyed2
");
    fclose($fp);
}
register_shutdown_function("shutdown_func");

while (true) {
    // do nothing
}
?>

shutdown_func gets called. So this means that class destuctor is not that good as shutdown functions.


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

...