Heim  >  Artikel  >  Backend-Entwicklung  >  一道三目运算符问题

一道三目运算符问题

WBOY
WBOYOriginal
2016-06-06 20:17:321317Durchsuche

<code>$a = 5;
$b = 10;
echo ($a) ? ($a == 5) ? 'yay' : 'nay' : ($b == 10) ? 'excessive' : ':('; 
</code>

不懂结果为什么是 "excessive" ? 求知道的朋友解答下

回复内容:

<code>$a = 5;
$b = 10;
echo ($a) ? ($a == 5) ? 'yay' : 'nay' : ($b == 10) ? 'excessive' : ':('; 
</code>

不懂结果为什么是 "excessive" ? 求知道的朋友解答下

通过修改数值,结合结果来分析吧

<code>//#1 excessive
$a = 5;
$b = 10;
echo ($a) ? ($a == 5) ? 1 : 0 : ($b == 10) ? 'excessive' : ':('; 

//#2 :(
$a = 3;
$b = 10;
echo ($a) ? ($a == 5) ? 1 : 0 : ($b == 10) ? 'excessive' : ':('; 


//#3 excessive
$a = 0;
$b = 10;
echo ($a) ? ($a == 5) ? 1 : 0 : ($b == 10) ? 'excessive' : ':('; 

//#4 :(
$a = 0;
$b = 9;
echo ($a) ? ($a == 5) ? 1 : 0 : ($b == 10) ? 'excessive' : ':('; </code>

可以看出$a为真时 执行($a == 5) ? 1 : 0 为假时执行 $b == 10
这个结果为真时返回excessive,为假时返回:(

为了方便阅读最好在($a == 5) ? 1 : 0 上加个括号

我只能说 js 跑出来是 yay

难道 PHP 是这样执行的?

<code class="php">($a ? ($a == 5 ? "yay" : "nay") : $b == 10) ? "excessive" : ":(";</code>

如果是自己写代码,还是加括号分组看起来方便些,比如下面这个应该是和 javascript 一样的结果。

<code class="php">echo $a
    ? ($a == 5 ? "yay" : "nay") 
    : ($b == 10 ? "excessive" : ":(");</code>

如果我猜的没错的话,要从后面往前面看,划分语句。
一道三目运算符问题

通过划分可以简化成
echo 'yay' ? 'excessive' : ':(';

<code><?php $a = 5;
$b = 10;
echo ($a) ? 

     (($a == 5) ? 'yay' : 'nay')

     : 
    
     (($b == 10) ? 'excessive' : ':('); 
</code></code>

这样结果就会变掉

<code>$a == 5 是真 返回yay</code>

($a) ? ($a == 5) ? 'yay' : 'nay' : ($b == 10) ? 'excessive' : ':('; 这种写法你是从左往右读的,但机器不这么读,它可能是这样读的 ($a) ? (($a == 5) ? 'yay' : 'nay' : ($b == 10) ? 'excessive') : ':('; 电脑头都晕了

$a ? ($a == 5 ? 'yay' : 'nay') : ($b == 10 ? 'excessive' : ':('); 以后这样写,好吗

在语言设计上,js重输出,而php重计算。
类似的差别还有&&符和||符的计算结果、null变成字符串后的结果等。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn