Zapic's Blog
PHP : 2 + 2 == 5
2020-04-18
查看标签

来了,人类迷惑行为大赏:

2+2=5

欢迎加入真理部
—— IzzelAliz's Blog - 2 + 2 == 5

只要够迷惑,你们就不能发现问题在哪,蛤↑蛤↑蛤↑

PHP没有Java那么复杂,所以实现原理很简单.

不如...
在阅读这篇文章时,你可以打开你浏览器的控制台,输入:

'2 + 2 = ' + (2 + 2 === 4 ? 4 : 2 + 2 === 5 ? 5 : 'neither')

得到2 + 2 = 4.
有条件的同学可以再开一个PHP Shell,输入:

echo '2 + 2 = ' . (2 + 2 === 4 ? 4 : 2 + 2 === 5 ? 5 : 'neither');

得到2 + 2 = 5.

方向反了,问题很大

绝大部分语言,三元表达式都是从右向左的:
例如,在JavaScript中,2 + 2 === 4 ? 4 : 2 + 2 === 5 ? 5 : 'neither'等价于2 + 2 === 4 ? 4 : (2 + 2 === 5 ? 5 : 'neither').
拆成if...else就是:

if(2 + 2 === 4) {
    console.log(4);
} else {
    if(2 + 2 === 5) {
        console.log(5);
    } else {
        console.log('neither');
    }
}

但是PHP就不一样了.
他是从左向右的.
所以,在PHP中,2 + 2 === 4 ? 4 : 2 + 2 === 5 ? 5 : 'neither'等价于(2 + 2 === 4 ? 4 : 2 + 2 === 5) ? 5 : 'neither'.
或者弄清楚些,我们拆成if...else:

if(2 + 2 === 4){
    $a = 4;
} else {
    $a = 2 + 2 === 5;
}
if($a){
    $b = 5;
} else {
    $b = 'neither';
}
var_dump($b);

But,I don't care!

2 + 2 =5

不许反驳.