dsbpaqt61965 2014-12-16 19:20
浏览 23

我应该在我的PHP代码中使用at符号(@)

I have recently learned how to use the @ symbol in my php code and I have learned to love it. However I have also been told that @ is not efficient performance wise. Is the elegance it provides enough to excuse the performance hit it might or might not create.

One common usage which I implement is in an if statement when trying to access an array.

if( $value = @$array['key'] )
// value exists and we can access it

Because it returns null instead of displaying an error it is a useful tool in situations as this one.

  • 写回答

2条回答 默认 最新

  • drhzn3911 2014-12-17 10:04
    关注

    Suppressing errors in this way is useful, but not for your example because there are more traditional ways to check for those potential errors.

    I use it sometimes, but normally for IO operations. For example.

    $sample = 'sample.txt';
    
    if (!file_exists($sample)) {
        throw new FileNotFoundException($sample);
    }
    
    if (!$fp = @fopen('sample.txt', 'r')) {
        throw new IOException($sample, error_get_last()['message']);
    }
    

    The exceptions in this are classes I would have created. The goal is to open a file for reading, first I need to check the file exists, thats easy, if it doesn't I can throw a relevant error.

    Next is to open the file. Well this is a nothing or all operation and there could be a multitude of reasons why it won't work (permissions for example).

    I want to handle the the problem if there is one (in this case by catching an exception) so I suppress the error (because I don't want users to see it), but I do want to know what happened, so I catch the exception, log the message somewhere and redirect the user somewhere else.

    I use @ because I don't know what the error might be and because depending on the PHP configuration it will always trigger an error regardless of what you do with the return value.

    Don't use it for something like getting an array value by index, because there are very few types of problems with this and they can all be checked for before starting the operation.

    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值