PHP 5.3.3拼图,它打印的内容和原因

时间:2011-10-14 10:36:05

标签: php puzzle ternary-operator

为什么它不打印要打印的内容?

<?php 
$place = 1; 
echo $place === 1 ? 'a' : $place === 2 ? 'b' : 'c'; 
?>

4 个答案:

答案 0 :(得分:8)

The manual is your friend。引用:

<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');

// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');

// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.

你基本上是这样做的:

echo ($place === 1 ? 'a' : $place === 2) ? 'b' : 'c';
// which is
echo 'a' ? 'b' : 'c';
// which is
echo 'b';

答案 1 :(得分:3)

echo ($place === 1 ? 'a' : $place === 2) ? 'b' : 'c';
echo ('a') ? 'b' : 'c';
echo (true) ? 'b' : 'c';
echo 'b';

这就是为什么。

答案 2 :(得分:1)

条件运算符从左到右进行求值,因此您应该编写

echo ($place === 1 ? 'a' : $place === 2)  ? 'b' : 'c';
echo (true         ? 'a' : $place === 2)  ? 'b' : 'c';
echo 'a'                                  ? 'b' : 'c';
echo true                                 ? 'b' : 'c'; // outputs b

澄清。此行为是well-documented

答案 3 :(得分:1)

您认为应该打印什么,为什么以及打印什么?

另外,从关于三元表达式的PHP手册:

  

注意:

     

建议您避免“堆叠”三元表达式。 PHP在单个语句中使用多个三元运算符时的行为是不明显的:

<?php

  // on first glance, the following appears to output 'true'
  echo (true?'true':false?'t':'f');

  // however, the actual output of the above is 't'
  // this is because ternary expressions are evaluated from left to right

  // the following is a more obvious version of the same code as above
  echo ((true ? 'true' : false) ? 't' : 'f');

  // here, you can see that the first expression is evaluated to 'true', which
  // in turn evaluates to (bool)true, thus returning the true branch of the
  // second ternary expression.

?>