简体   繁体   English

@ $ a或$ a =…在PHP中是什么意思?

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

I have seen in a TwitterOAuth's library of PHP this code: 我在TwitterOAuth的PHP库中看到了以下代码:

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. or仅在左侧为“ falsy”值时评估右侧( $parameters = array() )。

In this case, it can be read: 在这种情况下,它可以读取为:

Set $parameters to array() unless $parameters is already set $parameters设置$parameters array()除非已经设置了$parameters

The @ is unrelated to the or . @or不相关。 That is the error-suppression operator. 那就是错误抑制运算符。 In this case, it lets you test $parameters even if $parameters has not yet been assigned to. 在这种情况下,即使尚未分配$parameters ,它也可以测试$parameters 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. 表达式$parameters的第一部分将输出一条通知,如果未设置$ parameters,则结果为false。 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. 请注意,由于$ parameters是功能参数之一,因此将始终对其进行设置,因此不需要进行错误抑制。 The second part of the expression is only executed if the first part evaluates to false. 仅当第一部分的计算结果为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. 更一般而言,在确定包含和的布尔表达式的值时(在顶层),一旦找到真值,PHP将停止评估。

For example the following if statement will always be entered, and the second part of the expression will never be evaluated: 例如,将始终输入以下if语句,并且永远不会对表达式的第二部分求值:

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. 您发布的代码需要最少的输入,但是即使您了解发生了什么,它也可能需要更长的时间才能掌握。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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