@fopen($file);
忽略任何错误并继续
fopen($file) or die("Unable to retrieve file");
忽略错误,杀死程序和打印自定义消息
是有一种简单的方法可以忽略来自函数的错误,打印自定义错误消息而不是杀死程序?
@fopen($file);
忽略任何错误并继续
fopen($file) or die("Unable to retrieve file");
忽略错误,杀死程序和打印自定义消息
是有一种简单的方法可以忽略来自函数的错误,打印自定义错误消息而不是杀死程序?
典型:
if (!($fp = @fopen($file))) echo "Unable to retrieve file";
或使用方式(其中丢弃文件句柄):
@fopen($file) or printf("Unable to retrieve file");
使用异常:
try {
fopen($file);
} catch(Exception $e) {
/* whatever you want to do in case of an error */
}
fopen不会引发异常。 – JPot 2009-05-19 16:56:50
而不是死亡你可以抛出一个异常,并以你认为合适的方式集中处理错误处理:-)
slosd的方式将无法正常工作。 fopen不会引发异常。您应该手动thow它 我会修改你的第二个的exaple与slosd的结合起来:
try
{
if (!$f = fopen(...)) throw new Exception('Error opening file!');
}
catch (Exception $e)
{
echo $e->getMessage() . ' ' . $e->getFile() . ' at line ' . $e->getLine;
}
echo ' ... and the code continues ...';
这是我自己的解决方案。请注意,它需要脚本级别的全局变量或类的静态变量以便于参考。我写它的类风格作为参考,但只要它能找到数组就可以了。
class Controller {
static $errors = array();
}
$handle = fopen($file) or array_push(Controller::errors,
"File \"{$file}\" could not be opened.");
// ...print the errors in your view
如果你正确配置[display_errors设置](http://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors),则可以在保持饶@操作兼容性与显示错误(你应该只在开发时 - 如果有的话)。 – hakre 2011-06-03 13:08:34