PHP:析构函数vs register_shutdown_function [英] PHP: destructor 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\n");
fclose($fp);
}
};
$obj = new X();
while (true) {
// do nothing
}
?>
这是我发现的:
- 在Firefox中按STOP按钮不会停止此脚本
- 如果我关闭Apache,则析构函数不会被调用
- 当它到达PHP max_execution_time并且destuctor没有被调用时它停止
然而,执行此操作:
<?php
function shutdown_func() {
$fp = fopen("/var/www/htdocs/dtor.txt", "w+");
fputs($fp, "Destroyed2\n");
fclose($fp);
}
register_shutdown_function("shutdown_func");
while (true) {
// do nothing
}
?>
调用shutdown_func。所以这意味着类destuctor不如关闭函数那么好。
shutdown_func gets called. So this means that class destuctor is not that good as shutdown functions.
这篇关于PHP:析构函数vs register_shutdown_function的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!