Головоломка PHP 5.3.3, что она печатает и почему - PullRequest
2 голосов
/ 14 октября 2011

Почему не печатается то, что предполагается печатать?

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

Ответы [ 4 ]

8 голосов
/ 14 октября 2011

Мануал твой друг .Цитата:

<?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';
3 голосов
/ 14 октября 2011
echo ($place === 1 ? 'a' : $place === 2) ? 'b' : 'c';
echo ('a') ? 'b' : 'c';
echo (true) ? 'b' : 'c';
echo 'b';

Вот почему.

1 голос
/ 14 октября 2011

Как вы думаете, что это должно печатать и почему, и что печатается?

Кроме того, из руководства 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.

?>
1 голос
/ 14 октября 2011

Условный оператор вычисляется слева направо, поэтому вы должны написать

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

уточнить. Это поведение хорошо документировано .

...