tags:

views:

60

answers:

6

I have something 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.

+7  A: 

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.

Pekka
`echo` is a language construct and does not need parenthesis
Gordon
+2  A: 

Change

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

to

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

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>
murze
-1 for using short opening tags - a really bad idea and massively limits code portability, as (by default) they are disabled.
adam
I didn't know that short opening tags were disabled by default, I edited my answer so that the code will work with the regular php-tags
murze
Wicked. I can't unvote my downvote unless you edit your answer again
adam
A: 

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);
Gordon
+1  A: 

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"' : ''?>
Nicolò Martini
A: 

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

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