What is the purpose of '@' (silence operator, at sign) before trigger_error?

前端 未结 3 1697
南笙
南笙 2021-01-22 16:03

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

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

Accor

相关标签:
3条回答
  • 2021-01-22 16:31

    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.

    0 讨论(0)
  • 2021-01-22 16:34

    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.

    0 讨论(0)
  • 2021-01-22 16:46

    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.

    0 讨论(0)
提交回复
热议问题