>

Unexpected T_ECHO tag in string if

I have something similar 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 by T_ECHO. Changing echofor printsolves the problem, but I would like to understand why I can not use echo.

+3
source share
6 answers

You cannot use this construct in this way. the ternary operator is not an "if" block, but returns a value based on whether the condition is met or not.

You want to change the structure:

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

print(), . , , echo print, .

echo, , .

+9

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

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

:

echo() (it ), . echo() ( ) , . , echo(), .

:

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

, .

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

, :

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

imho

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

I would drop the ternary operator and the empty print string and write:

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

Source: https://habr.com/ru/post/1738504/


All Articles