Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

php - underlying difference between elseif vs else if

I was wondering the differnce between elseif and else if.

I was reading the manual which says if using the braces {} they are treated the same but only elseif works when not using the braces.

Also another contributer said:

Note that } elseif() { is somewhat faster than } else if() {

and he backed it up with a benchmark test.

To me it seems like elseif is the true way of saying it and saying:

else if() {...}

is really the equivalent of:

else { if() {...} }

which might explain why its marginally slower.

I am used to using else if because thats how I do it in other languages as well. I don't really think it matters which way you type it (unless you are not using braces.. but I think its always good to use braces anyways) I was just curious about the underlying details.

Am I correct?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In addition to my comment, from what I can see in the PHP source, the only speed boost is that PHP's parser has a special token for elseif, unsurprisingly known as T_ELSEIF. But I'm sure the speed boost is nothing more than a side effect of allowing elseif in the alternative syntax:

if (cond1):
    // Do something
elseif (cond2):
    // Do something else
else:
    // Do something else
endif;

Similar to Python, which uses elif, else if with a space wouldn't be allowed without having to unnecessarily complicate the parser's implementation code (i.e. to act differently between seeing a colon and the if keyword). So a colon is required directly after else and if respectively, and that's how the language rule is stipulated.

Ergo I'm pretty sure PHP just treats else if as a conditional block in a singular-statement else.

If there are any speed differences at all, blame the parser for most of them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...