问题
I was studying about ternary operation nesting and made some tests with this routine:
<?php
$test1 = [15,30,'ok'];
$test2 = [8,90,'fail'];
$test3 = [4,32,'ok'];
$test1[2] == 'ok' ?
print('First passed. The second round marks '.
$test2[1]/$test2[0] < 10 ? 'an irrelevant value' : $test2[1]/$test2[0].
' and the third was skipped.') :
print('First failed. The second round was skipped and the third marks '.
$test3[1]/$test3[0] < 10 ? 'an irrelevant value' : $test3[1]/$test3[0]);
Although I know why it's not printing the string in the way I'd expect (it ignores everything before conditional test) because it lacks parenthesis around the ternary operator, it's showing some curious behavior despite of that. It's inverting the operator's evaluation priority.
Example
This test, written as it is, should return 11.25
since 11.25 > 10
, but instead it returns an irrelevant value
!
If I change the <
operator for >
, it should then print an irrelevant value
, since it's true
, but it evaluates to false
and print 11.25
anyway.
Can anyone explain to me why it happens? Like I've said, I know the above statement is syntactically wrong, but I'm willing to understand why it alters the way PHP works the logic.
回答1:
http://php.net/manual/en/language.operators.precedence.php lists the PHP operators with their precedence. According to this table,
'First passed. The second round marks ' . $test2[1] / $test2[0] < 10
? 'an irrelevant value'
: $test2[1] / $test2[0] . ' and the third was skipped.'
parses as
(('First passed. The second round marks ' . ($test2[1] / $test2[0])) < 10)
? 'an irrelevant value'
: (($test2[1] / $test2[0]) . ' and the third was skipped.')
/
binds tighter than.
.
binds tighter than<
<
binds tighter than?:
In other words, you're comparing the string 'First passed. The second round marks 11.25'
to the number 10
.
来源:https://stackoverflow.com/questions/32781683/why-is-ternary-operator-ignoring-condition-order