找回密码
 新猫注册
查看: 908|回复: 0

Dying with grace - PHP’s register_shutdown_function

[复制链接]
kernel 发表于 2008-10-20 17:39:05 | 显示全部楼层 |阅读模式
http://eirikhoem.wordpress.com/2 ... _shutdown_function/

I guess I didn’t make the purpose quite clear here. This method will allow you to show custom error messages when PHP hits a fatal error. The shutdown function will always run.

Scripts tend to die, and that’s not usually nice. We do not want to show the user a fatal error nor a blank page (display errors off) . PHP has a function called register_shutdown_function which lets us set up a function which is called at execution shutdown. What this means is that our function will be executed when our script is done executing / dying and PHP execution is about to shut down. By setting up a variable to false at the start of our script, and setting it to true at the very end of the script we can have our shutdown function check if the script completed successfully or not. If our variable is still false we know that we never made it to the last line of our script, hence it died somewhere. I’ve prepared a very basic sample which shows how you can give the user some proper feedback if a fatal error should arise. You’d want to turn of display of fatal errors for this to look nice.

<?php
$clean = false;
function shutdown_func(){
global $clean;
if (!$clean){
die(”not a clean shutdown”);
}
}

register_shutdown_function(’shutdown_func’);

$a = 1;
$a = new FooClass(); // will fail with fatal

$clean = true;
?>

As you can see, the shutdown_func prints something if the clean variable isn’t set to true when the shutdown function runs. This should of course be wrapped in a class (and NOT use globals), and for something more usable I recommend checking EZ Components way of doing this.
您需要登录后才可以回帖 登录 | 新猫注册

本版积分规则

手机版|小黑屋|[漫猫]动漫论坛

GMT+8, 2024-11-21 17:54

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表