register_shutdown_function vs __destruct

php中为什么有了 __destruct函数后还没有把register_shutdown_function 置为deprecated ?

代码说明一切:

<?php
class T1
{
function __construct()
{
register_shutdown_function(array(&$this, 'shutdown_func'));
}

function shutdown_func() {
$fp = fopen("/tmp/t1.txt", "w+");
fputs($fp, "向我开炮\n");
fclose($fp);
}
};

$obj = new T1();
while (true) {
// do nothing
}
执行:
Fatal error: Maximum execution time of 30 seconds exceeded in /home/hanyh/workspace/website/t1.php on line 19
结果:
hanyh@hanyh:~/workspace/git/django-pagination$ more /tmp/t1.txt
向我开炮

<?php
class T2
{
function __destruct()
{
$fp = fopen("/tmp/t2.txt", "w+");
fputs($fp, "向我开炮\n");
fclose($fp);
}
};

$obj = new T2();
while (true) {
// do nothing
}
执行:
Fatal error: Maximum execution time of 30 seconds exceeded in /home/hanyh/workspace/website/t2.php on line 13
结果:
hanyh@hanyh:~/workspace/git/django-pagination$ more /tmp/t2.txt
/tmp/t2.txt: 没有该文件或目录

由对比可知,使用register_shutdown_function才能保证即使脚本异常中止时,清理函数的代码仍然能够执行。所以在代码中必须在脚本退出时清理资源时,需要使用register_shutdown_function。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章