php - 三元运算符左结合性

标签 php ternary-operator associativity

<分区>

在 PHP 手册中,我找到了 the following 'user contributed note'在“运营商”下。

Note that in php the ternary operator ?: has a left associativity unlike in C and C++ where it has right associativity.

You cannot write code like this (as you may have accustomed to in C/C++):

<?php 
$a = 2; 
echo ( 
    $a == 1 ? 'one' : 
    $a == 2 ? 'two' : 
    $a == 3 ? 'three' : 
    $a == 4 ? 'four' : 'other'); 
echo "\n"; 
// prints 'four' 

我实际尝试了一下,它确实打印了 four。但是我无法理解它背后的原因,仍然觉得它应该打印 twoother

有人可以解释这里发生了什么以及为什么它打印“四”吗?

最佳答案

在任何理智的语言中,三元运算符都是右结合的,因此您期望您的代码被解释成这样:

$a = 2;
echo ($a == 1 ? 'one' :
     ($a == 2 ? 'two' :
     ($a == 3 ? 'three' :
     ($a == 4 ? 'four' : 'other'))));    # prints 'two'

但是,PHP 三元运算符是奇怪的左结合运算符,因此您的代码实际上等同于:

<?php
$a = 2;
echo (((($a == 1  ? 'one' :
         $a == 2) ? 'two' :
         $a == 3) ? 'three' :
         $a == 4) ? 'four' : 'other');   # prints 'four'

如果还是不清楚,可以这样评价:

echo ((((FALSE    ? 'one' :
         TRUE)    ? 'two' :
         $a == 3) ? 'three' :
         $a == 4) ? 'four' : 'other');

echo ((( TRUE     ? 'two' :
         $a == 3) ? 'three' :
         $a == 4) ? 'four' : 'other');

echo ((  'two'    ? 'three' :
         $a == 4) ? 'four' : 'other');

echo (    'three' ? 'four' : 'other');

echo 'four';

关于php - 三元运算符左结合性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20559150/

相关文章:

php - 三元运算符。有可能单方面行动吗?

coding-style - 在线条件表达式或函数 - Pythonic?

c - C 中的运算符优先级

xml - XPath 中运算符的优先级是什么?

php - 试图从命名空间 (...) 加载类 "ClassName"。即使命名空间被导入

php - 使用 idiorm 和 php 更新一行

php - 从类的公共(public)函数中检索 mysql 字段的值

c++ - 运行 while 的第一个实例

c++ - 括号可以覆盖表达式的求值顺序吗?

php - 为什么 mb_convert_case 在 PHP 5.4 中破坏了我的字符串,而在 5.2 中却没有?