Reputation:
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?
Upvotes: 1
Views: 1446
Reputation: 6976
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.
Upvotes: 1
Reputation: 239311
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
toarray()
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.
Upvotes: 1