下边这些话是PHP手册上说的,我比较好奇的是为何PHP会同时存在这两种写法呢?
elseif,和此名称暗示的一样,是 if 和 else 的组合。和 else 一样,它延伸了 if语句,可以在原来的 if 表达式值为 FALSE时执行不同语句。但是和 else 不一样的是,它仅在 elseif 的条件表达式值为 TRUE时执行语句。例如以下代码将根据条件分别显示 a is bigger than b,a equal to b 或者 a is smaller than b:
<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?> 在同一个 if 结构中可以有多个 elseif 语句。第一个表达式值为 TRUE 的 elseif 语句(如果有的话)将会执行。在 PHP 中,也可以写成“else if”(两个单词),它和“elseif”(一个单词)的行为完全一样。句法分析的含义有少许区别(如果你熟悉 C 语言的话,这是同样的行为),但是底线是两者会产生完全一样的行为。 elseif 的语句仅在之前的 if 或 elseif 的表达式值为 FALSE,而当前的 elseif 表达式值为 TRUE 时执行。 Note: 必须要注意的是 elseif 与 else if 只有在类似上例中使用大括号的情况下才认为是完全相同 Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error.
elseif,和此名称暗示的一样,是 if 和 else 的组合。和 else 一样,它延伸了 if语句,可以在原来的 if 表达式值为 FALSE时执行不同语句。但是和 else 不一样的是,它仅在 elseif 的条件表达式值为 TRUE时执行语句。例如以下代码将根据条件分别显示 a is bigger than b,a equal to b 或者 a is smaller than b:
<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?> 在同一个 if 结构中可以有多个 elseif 语句。第一个表达式值为 TRUE 的 elseif 语句(如果有的话)将会执行。在 PHP 中,也可以写成“else if”(两个单词),它和“elseif”(一个单词)的行为完全一样。句法分析的含义有少许区别(如果你熟悉 C 语言的话,这是同样的行为),但是底线是两者会产生完全一样的行为。 elseif 的语句仅在之前的 if 或 elseif 的表达式值为 FALSE,而当前的 elseif 表达式值为 TRUE 时执行。 Note: 必须要注意的是 elseif 与 else if 只有在类似上例中使用大括号的情况下才认为是完全相同 Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error.
} elseif() {
} else {
}if() {
} else {
if() {
}else {
}
}你是指这两者的区别吗?
很显然,前者通过 elseif 提升了子判断的级别
if(){
}else if(){
}elseif(){
}else{
}
}else if(){
}elseif(){
}else{
}
而
if(){
}elseif(){
}elseif(){
}else{
}等同于
switch
case
csae
case
default
}else if(){//注意这个else和if之间有一个空格
}elseif(){//注意这个else和if之间有没空格
}else{
}
今天看楼主发这个,才忽然意识到。else if( ... ){
....
}
应该是
else{
if( ... ){
....
}
}
这个意思。因为if或else的代码快如果不用大括号包起来,只作用于紧接着的一行。就像我们有时if的下面只有一行代码,我们会懒得写大括号:已知
if(1)
echo true;
和
if(1) echo true;
是一样的。
那么
else if( 1 ) echo true;
此句中的echo true就相当于那个if,而此代码中的if,相当于那个else。也就是说,else if的这个if,类似是else的分支一般。而elseif,则它俩共同属于一个分支。这应该就是手册原文中"句法分析的含义有少许区别"这句话的意思。而真的写出来,他俩的实际表现是相同的效果。