Вопрос по operator-precedence, php, ternary-operator, order-of-evaluation – Как я могу понять вложенные?: Операторы в PHP? [Дубликат]
Possible Duplicate:
Problem with PHP ternary operator
Я немного читал на PHP вЭта статьяи я остановился на некоторое время, чтобы рассмотреть один из его жалоб. Я не могу понять, как PHP приходит к такому результату.
Unlike (literally!) every other language with a similar operator, ?: is left associative. So this:
$arg = 'T';
$vehicle = ( ( $arg == 'B' ) ? 'bus' :
( $arg == 'A' ) ? 'airplane' :
( $arg == 'T' ) ? 'train' :
( $arg == 'C' ) ? 'car' :
( $arg == 'H' ) ? 'horse' :
'feet' );
echo $vehicle;
prints horse.
По какому логическому пути следует PHP, что приводит к'horse'
быть назначенным на$vehicle
?
Брекетинг - это решение для пониманияand фиксирование:
Это должно иметьunintended результат (horse
):
$arg = 'T';
$vehicle = (
(
(
(
(
( $arg == 'B' ) ? 'bus' : ( $arg == 'A' )
) ? 'airplane' : ( $arg == 'T' )
) ? 'train' : ( $arg == 'C' )
) ? 'car' : ( $arg == 'H' )
) ? 'horse' : 'feet'
);
echo $vehicle;
Это должно иметь результат с отступом (train
):
$arg = 'T';
$vehicle = (
( $arg == 'B' ) ? 'bus' : (
( $arg == 'A' ) ? 'airplane' : (
( $arg == 'T' ) ? 'train' : (
( $arg == 'C' ) ? 'car' : (
( $arg == 'H' ) ? 'horse' : 'feet'
)
)
)
)
);
echo $vehicle;
Note:
It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:
<?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. ?>
http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary