What is the purpose of '@' (silence operat

2019-03-01 09:00发布

I have seen in many Symfony bundles (and also in other codes) this line :

@trigger_error('The class is deprecated', E_USER_DEPRECATED);

According to the documentation, the @ (at) operator is used to silence the errors (http://php.net/manual/en/language.operators.errorcontrol.php).

So, what is the purpose of throwing a silenced error?

3条回答
女痞
2楼-- · 2019-03-01 09:24

Adding to what other people said, according to the docs this entire scheme boils down to the following example:

set_error_handler(function ($errno, $errstr) {
    var_dump($errstr); // outputs "Will only be seen ..."
}, E_USER_DEPRECATED);

@trigger_error('Will only be seen from a custom error handler', E_USER_DEPRECATED);

Otherwise put, a silenced deprecation notice still can be heard from a custom error handler, if needed, not polluting the usual logs in the same time.

查看更多
Emotional °昔
3楼-- · 2019-03-01 09:34

As stated in the Symfony coding conventions:

Without the @-silencing operator, users would need to opt-out from deprecation notices. Silencing swaps this behavior and allows users to opt-in when they are ready to cope with them (by adding a custom error handler like the one used by the Web Debug Toolbar or by the PHPUnit bridge).

Comment from author about the relevant PR:

...There is an other consideration that makes me think this is really the best: performance. We could wrap the implementation of triggering "opt-in deprecation notices" behind some more semantic interface. But that would add overhead to something that needs to be as fast as possible. This is not a micro-optim when this can be called thousands of times. Thus this raw-bare-metal-php implementation that may look hacky, but is just the right implementation for our needs.

查看更多
【Aperson】
4楼-- · 2019-03-01 09:35

Just speculating, but this could be used to be handled by a custom error handler.

Example:

set_error_handler(function ($err_severity, $err_msg, $err_file, $err_line, array $err_context)
{
    //Log the error 

    // error was suppressed with the @-operator
    if (0 === error_reporting()) { 
        return false;
    }
   // handle error

 }

Therefore the error can be logged (or otherwise handled) even if it is suppressed.

You can't know exactly why this is done unless there's documentation about it. It's up to the developers to explain why they do this.

查看更多
登录 后发表回答