简体   繁体   中英

What does @$a or $a = … mean in PHP?

I have seen in a TwitterOAuth's library of PHP this code:

function __construct($http_method, $http_url, $parameters=NULL) {
    @$parameters or $parameters = array();
    //...
}

What does the operator or mean in this case?

The or evaluates the right-hand side ( $parameters = array() ) only if the left-hand side is a "falsy" value.

In this case, it can be read:

Set $parameters to array() unless $parameters is already set

The @ is unrelated to the or . That is the error-suppression operator. In this case, it lets you test $parameters even if $parameters has not yet been assigned to. Typically this would cause an error, as it's a pretty commonly accepted best-practice to turn on error reporting when you attempt to read from a variable that has not yet been assigned to.

This is a shorthand for

if( empty($parameters) ) {
    $parameters = array();
}

The first part of the expression $parameters will output a notice and evaluate to false if $parameters is not set. The @ symbol suppresses that notice. Note that since $parameters is one of the function parameters it will always be set, so the error suppression is not necessary. The second part of the expression is only executed if the first part evaluates to false.

More generally, when determining the value of a boolean expression containing and OR (at the top level), PHP will stop evaluating once it finds a truthy value.

For example the following if statement will always be entered, and the second part of the expression will never be evaluated:

if( true || $anything ) {
     //will always be executed
}

As a side note, I think it is better to be expressive rather than clever. The code you posted requires minimal typing, but even if you understand what's happening it may take longer to grasp.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM