PHP if...else 替代语法抛出 "unexpected ':' in..." 错误消息

PHP if... else alternative syntax throwing "unexpected ':' in..." error message

我需要一些有关以下替代 if-else 语法的帮助。 我经常使用它,它的成功率为 99.999999%。 在这里,出于某种原因,它没有:

if ( get_row_layout() == 'spacer' ) : 

    $spaceheight = get_sub_field('spacer_height');

    // The Alternative Syntax: if... else statement without a colon
    // Once these two lines are removed OR changed into "if ( some
    // condition ) : some stuff; endif;" syntax >> the error goes
    // away. 
    if ( $spaceheight && ( 0 !== $spaceheight ) )
        echo "<div class='basf-spacer' style='display: block; width: 100%; height: {$spaceheight}px; background: transparent; padding: 0; margin: 0; font-size: 0; line-height: 0;'></div>";

elseif ( get_row_layout() == 'terms' ) :

    // Some other stuff

endif;

具体报错信息为:"Parse error: syntax error, unexpected ':' in... "; elseif ( get_row_layout() == 'terms' ) : 行中的替代语法后冒号是意外的。

知道这里发生了什么吗?


@antoni 建议的答案是不能混合使用替代语法。 但在这种情况下,为什么会这样呢?:

if ( $terms_primcont || $terms_seccont ) : ?>

    <div class="terms__body-wrap">

        <?php 
        if ( $terms_primcont ) echo "<div class='terms__primary'>{$terms_primcont}</div>";
        if ( $terms_seccont ) echo "<div class='terms__secondary'>{$terms_seccont}</div>";
        ?>

    </div>

<?php endif;

发生这种情况是因为您混合了嵌套的 2 个语法 if。如果你这样做,它将起作用:

<?php
function get_row_layout(){}

if ( get_row_layout() == 'spacer' ) :

    $spaceheight = get_sub_field('spacer_height');

    // The Alternative Syntax: if... else statement without a colon
    // Once these two lines are removed OR changed into "if ( some
    // condition ) : some stuff; endif;" syntax >> the error goes
    // away.
    if ( $spaceheight && ( 0 !== $spaceheight ) ) :
        echo "<div class='basf-spacer' style='display: block; width: 100%; height: {$spaceheight}px; background: transparent; padding: 0; margin: 0; font-size: 0; line-height: 0;'></div>";
    endif;
elseif ( get_row_layout() == 'terms' ) :

    // Some other stuff

endif;

?>

[编辑] 问题编辑后:

它不能很好地与 elseif 混合你可以试试这个也有喙:

$terms_primcont = 1;
$terms_seccont = 1;
if ( $terms_primcont || $terms_seccont ) :

    echo "<div class=\"terms__body-wrap\">";


        if ( $terms_primcont )
            echo "<div class='terms__primary'>{$terms_primcont}</div>";
        if ( $terms_seccont )
            echo "<div class='terms__secondary'>{$terms_seccont}</div>";


    echo '</div>';

elseif (1 === 2)
    // never do sth.
endif;