PHP如果...否则抛出"unexpected ':' in..."错误消息的替代语法



我需要以下替代方案IF-else语法的帮助。我经常使用它,并且成功率为99.99999%。由于某种原因,在这里没有:

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;

特定错误消息是:"解析错误:语法错误,意外":'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个语法混合。如果这样做,它将起作用:

<?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; 

最新更新