【问题标题】:What does this 'or' do on the left hand side of a PHP assignment statement?这个“或”在 PHP 赋值语句的左侧有什么作用?
【发布时间】:2015-01-15 00:03:47
【问题描述】:

我正在研究一些 OAuth 的东西,并发现了这行有趣的代码:

$port or $port = ($scheme == 'https') ? '443' : '80';

我不熟悉赋值语句左侧的 or 关键字。

我希望 $a 或 = ($b=$c); 相当于 $a = $a 或 ($b=$c); 以类似的方式 $str.=" 附加到 str"; 相当于 $str=$str."将此附加到 str";

在帮助中搜索“或”会呈现许多结果!因此我转向了stackoverflow....

谁能告诉我作业左侧的“或”关键字的作用。

在上下文中,整个功能是:

public static function php_self($dropqs = true) {
    $url = sprintf ( '%s://%s%s', empty ( $_SERVER ['HTTPS'] ) ? (@$_SERVER ['SERVER_PORT'] == '443' ? 'https' : 'http') : 'http', $_SERVER ['SERVER_NAME'], $_SERVER ['REQUEST_URI'] );

    $parts = parse_url ( $url );

    $port = $_SERVER ['SERVER_PORT'];
    $scheme = $parts ['scheme'];
    $host = $parts ['host'];
    $path = @$parts ['path'];
    $qs = @$parts ['query'];

    $port or $port = ($scheme == 'https') ? '443' : '80';

    if (($scheme == 'https' && $port != '443') || ($scheme == 'http' && $port != '80')) {
        $host = "$host:$port";
    }
    $url = "$scheme://$host$path";
    if (! $dropqs)
        return "{$url}?{$qs}";
    else
        return $url;
}

【问题讨论】:

    标签: php variable-assignment


    【解决方案1】:

    它基本上是这样说的:

    if ($port==0) { 
      $port = ($scheme == 'https') ? '443' : '80';
    }
    

    一对表达式本身带有布尔值 or 将评估左值,如果为真,将停在那里。如果左边的值是假的,它将继续评估右边的值。所以,

    $a or $b
    

    当 $a 为布尔真值时将评估为 $a,当 $a 为布尔值 false 时将评估为 $b。

    虽然它有效,但它违反了常见的编码实践。例如,它可以写得更清楚,如我所展示的那样。

    【讨论】:

      【解决方案2】:

      这等价于:

      if (!$port) {
          $port = ($scheme == 'https') ? '443' : '80';
      }
      

      它使用or 运算符的短路来定义$port(如果尚未定义);如果A or B 中的第一个表达式计算结果为true,则不需要计算第二个表达式。

      【讨论】:

        猜你喜欢
        • 2023-04-03
        • 2016-06-08
        • 1970-01-01
        • 2019-05-09
        • 1970-01-01
        • 2016-11-25
        • 2011-05-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多