PHP:析构函数 vs register_shutdown_function [英] PHP: destructor vs register_shutdown_function

查看:27
本文介绍了PHP:析构函数 vs register_shutdown_function的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 PHP 类,可以动态创建 PNG 图像并将其发送到浏览器.PHP 手册说我需要确保在最后调用 imagedestroy 函数以释放内存.现在,如果我不使用类,我会有这样的代码:

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");

但是,我认为适合我的班级的地方是在班级的析构函数中调用 imagedestroy.

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

我没有发现析构函数是否像关闭函数一样被调用?例如,如果用户在浏览器中按下 STOP 按钮时执行停止.

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.

注意:无论您在答案中写什么,请指向支持它的文章或手册页 (URL).

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

推荐答案

我刚刚用 Apache 进行了测试,PHP 被用作 Apache 模块.我创建了一个这样的无限循环:

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
}
?>

这是我发现的:

  • 在 Firefox 中按 STOP 按钮不会停止此脚本
  • 如果我关闭 Apache,则不会调用析构函数
  • 它在达到 PHP max_execution_time 时停止,并且不会调用 destructor

但是,这样做:

<?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 被调用.所以这意味着类析构函数不如关闭函数.

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

这篇关于PHP:析构函数 vs register_shutdown_function的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆