开发者

Unexpected tag T_ECHO in inline if

I have something 开发者_Go百科like this in one of my views

<li <?php $isCurrent ? echo 'class="current"' : ''?> >
    <a href="SOME_LINK" class="SOME_CLASS">SOME_TEXT</a>
</li>

This causes a syntax error, unexpected T_ECHO. Changing echo for print solves the issue, but I would like to understand why I cannot use echo.


You can't use this construct that way. The ternary operator is not an "if" block, but returns a value based on whether the condition is fulfilled or not.

You want to change the structure:

<?php echo  ($isCurrent ? 'class="current"' : '') ?>

it works with print() because that is a function with a return value. It is however not what you want, because the first echo will print out the result of print which makes no sense.

It doesn't work with echo because echo is not a function, but a language construct.


Change

<?php $isCurrent ? echo 'class="current"' : ''?>

to

<?php echo $isCurrent ? 'class="current"' : ''?>


From the documentation:

echo() is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo() (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo(), the parameters must not be enclosed within parentheses.

This instead works fine:

<?php $isCurrent ? print('class="current"') : ''?>

Anyway, it's bad coding. Better is

<?php echo $isCurrent ? 'class="current"' : ''?>


This is much easier to read and handle imho

<?php printf('<li%s><a href="%s" class="%s">%s</a></li>',
              $isCurrent ? ' class="current"' : '',
              $someLink, $someClass, $someText);


I would drop the ternary operator and the empty printed string altogether and write:

<?php
$isCurrent and print 'class="current"';
?>


I think this small fix will solve your problem:

<li <?php echo ($isCurrent ? 'class="current"' : '')?> >
    <a href="SOME_LINK" class="SOME_CLASS">SOME_TEXT</a>
</li>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜