I think ternary is great in templates.
<div id="post" class="isFlagged) ? ‘flagged’ : ‘unflagged’; ?>”>
getBody(); ?>
The benefit of the ternary operator is debatable (there’s only one, by the way). Here is a line of code from an audit we performed recently:
1 2 3 | <?php $host = strlen($host) > 0 ? $host : htmlentities($host); ?> |
Oops! The author actually means to escape $host if the string length is greater than zero, but instead accidentally does the opposite. Easy mistake to make? Maybe. Easy to miss during a code audit? Certainly. Concision doesn’t necessarily make the code any better.
The ternary operator may be fine for one-liners, prototypes, and templates, but we strongly believe that an ordinary conditional statement is almost always better. PHP is descriptive and verbose. We think code should be, too.
I think ternary is great in templates.
<div id="post" class="isFlagged) ? ‘flagged’ : ‘unflagged’; ?>”>
getBody(); ?>
lol… your replies don’t allow php tags… which makes it hard to discuss php code…
You can now post code in comments by wrapping code in [ code ] [/ code ] minus the spacing of course.
$foo = "Code in Comment";
echo $foo;
I’m not sure why you wouldn’t just do:
$host = htmlentities($host);
The ternary operator is like a gun – if you don’t know how it works, you shouldn’t use it. The example you gave doesn’t strike me as confusing in the least, but I do agree that it would be clearer with something like
if(!empty($host)) $host = htmlentities($host);
That said, I do like to use the ternary for dealing with default values, e.g.:
$host = isset($row['host']) ? $row['host'] : 'localhost';
and I really like the ability to leave out the middle condition since 5.3, much like the “or equal” ruby operator.
Personally I use them when ever possible, like most tools of the trade it has its uses, but can be abused.
May 19, 2011 at 7:16 pm