Home  >  Article  >  Backend Development  >  PHP三元运算符的结合性介绍_PHP

PHP三元运算符的结合性介绍_PHP

WBOY
WBOYOriginal
2016-06-01 12:14:15973browse

先看一个三元运算式子:

复制代码 代码如下:
$a=1;$b=2;$c=3;$d=4;
echo $a?>

一般按照其它语言(比如C或Java)的规则, 以上代码的运算逻辑是:

复制代码 代码如下:
$a true => 'xx' ==> 结束

那么最后得到的结果就是'xx', 而再往后的运算都会被无视.
然而令人吃惊的是, php运算以上代码最后得到的结果却是'zz'...我擦, 什么情况, 这不坑爹么...
老规矩, 只好求教谷歌酱, 结果被告知php的三元运算竟然是向左结合的...于是豁然开窍.
我给上面的代码加上两个括号:

复制代码 代码如下:
$a=1;$b=2;$c=3;$d=4;
echo (($a?>

一目了然了吧, 这才是php的运算逻辑:

复制代码 代码如下:
$a true => 'xx' => true => 'yy' => true => 'zz' => 结束

这其中涉及到两个类型转化的过程, 即 'xx' => true 和 'xx' => true.
不知这样的过程是否是蛋疼, 确实是让人很难理解...
最后再次回到上面的代码, 将其变为像C一样的向右结合吧:

复制代码 代码如下:
$a=1;$b=2;$c=3;$d=4;
echo $a// 括号换下位置就行了, php里括号省不得
?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn