博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

学习笔记——php利用@来抑制错误

Posted on 2011-08-11 17:21  bug yang  阅读(645)  评论(0编辑  收藏  举报
利用@来抑制错误

在PHP中,可以使用@运算符来抑制单个错误。例如,如果不希望PHP报告它不包括某个文件,则可以编写如下代码:

@include ('config.inc.php');

或者如果不希望看到“除以0”错误:

$x = 8;

$y = 0;

$num = @($x/$y);

像函数调用或数学运算一样,@符号只能处理表达式。不能在条件语句、循环语句、函数定义等之前使用@符号。

一条经验法则是,我建议将@符号用于那些执行失败时不会影响脚本整体功能的函数。或者,在你自己可以更优雅地处理PHP的错误时可以抑制错误(本章后面将讨论这个主题)。

一些开源软件中使用到@抑制错误的部分代码:

  1. //code from phpbb3(common.php)  
  2. // If we are on PHP >= 6.0.0 we do not need some code  
  3. if (version_compare(PHP_VERSION, '6.0.0-dev''>='))  
  4. {  
  5.  /** 
  6.  * @ignore 
  7.  */  
  8.  define('STRIP', false);  
  9. }  
  10. else  
  11. {  
  12.  @set_magic_quotes_runtime(0);  
  13.   
  14.  // Be paranoid with passed vars  
  15.  if (@ini_get('register_globals') == '1' || strtolower(@ini_get('register_globals')) == 'on' || !function_exists('ini_get'))  
  16.  {  
  17.   deregister_globals();  
  18.  }  
  19.   
  20.  define('STRIP', (get_magic_quotes_gpc()) ? true : false);  
  21. }  
  22.   
  23. //code from phpbb3(style.php)  
  24. $dir = @opendir("{$phpbb_root_path}styles/{$theme['theme_path']}/theme");  
  25.   
  26. //code from phpbb3(adm/index.php)  
  27.                     if (file_exists($phpbb_root_path . $cfg_array[$config_name]) && !@is_writable($phpbb_root_path . $cfg_array[$config_name]))  
  28.                     {  
  29.                         $error[] = sprintf($user->lang['DIRECTORY_NOT_WRITABLE'], $cfg_array[$config_name]);  
  30.                     }  
  31.   
  32. //code from phpbb3(functions.php)  
  33.     if (($fh = @fopen('/dev/urandom''rb')))  
  34.     {  
  35.         $random = fread($fh$count);  
  36.         fclose($fh);  
  37.     }