这个“or”在 PHP 赋值语句的左侧做什么


What does this 'or' do on the left hand side of a PHP assignment statement?

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

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

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

我期待 $a 或 = ($b=$c);将等同于 $a = $a 或 ($b=$c);以类似于 $str.=" 将此附加到 str";相当于 $str=$str。"将此附加到 str";

在帮助中搜索"or"会呈现许多结果!因此,我转向了堆栈溢出。

有人可以告诉我作业左侧的"or"关键字的作用吗?

在上下文中,整个函数是:

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;
}

这等效于以下内容:

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

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

它基本上会说与以下内容相同:

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

一对表达式本身与布尔值或将计算左值,如果它为真,将停止到此。如果左边的值为假,它将继续计算右边的值。 所以

$a or $b

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

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