2015-04-12 71 views
6

PHP,我喜欢用的一个功能是结肠风格的if语句(我不知道它实际上叫。)if和else if在PHP中,结肠风格

<?php if(something):?> 
    <html stuff> 
<?php endif;?> 

但我最近试图用多种情况下做到这一点:

<?php if(something):?> 
    <html stuff> 
<?php else if(something):?> 
    <html stuff> 
<?php endif;?> 

,我就上三线(else if)的错误:

Unexpected T_IF

如果这种方式可以做一个if-else吗?

+2

我没有downvote,但我不认为这是值得张贴问题,特别是没有,如果你已经解决了这个问题(你回答了你自己的问题立即)。这只是一个语法错误,它被认为是“脱离主题” – hek2mgl

+1

@ hek2mgl尽管这不是排印错误。当我写这个问题时,我确实解决了我的问题,但我认为社区可以从这个问题中提供的知识中受益。否则如果(2个字)在PHP中完全有效;这不是一个印刷错误。 – David

+0

@MathNerdProductions 1.'Parse error:'**语法错误,**'意外'if'(T_IF)'这是一个语法错误。 2.每个阅读手册的人都知道这个 – Rizier123

回答

7

我能够得到它的工作。

在这个非常特殊的情况下,else ifelseif不同义。

elseif代替else if解决了这个问题。

<?php if(something):?> 
    <html stuff> 
<?php elseif(something):?> 
    <html stuff> 
<?php endif;?> 

PHP.net

Note: 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.

+2

这可能是值得包括来自[此评论](http://php.net/manual/en/control-structures.elseif.php#115851)关于*为什么它不起作用的解释。也就是说'else if'实际上是一个单语句'else',它的语句恰好是'if',并且冒号在替代语法中不是可选的,与正常语法中的{}不同。 – IMSoP