26 Oct 2007
In Defence of PHP Short Tags
On most servers, PHP will happily let you begin a block of code with either
<?php or just
<? , but the latter is widely frowned upon. Spend a few minutes Googling and you could be forgiven for getting the impression short tags are thoroughly evil and will eat your code/children while you sleep.
Not everyone has them enabled, so you need to avoid short tags for maximum compatibility, but why disable them in the first place? Aside from circular reasoning (disable them because they’re bad; they’re bad because some have them disabled), all I can see are misleading asides (scroll down to ‘Note:’) and grumbles about ‘incompatibility’ with XML/XHTML. Why would you expect to be able to parse unmodified XML markup as PHP code without potential problems, or validate PHP code as XML markup? It’s just not reasonable or necessary. Oh, and you only need to add 4 characters to an XML declaration/processing instruction within a PHP file to avoid a clash, e.g.:
<<??>?xml version="1.0" encoding="UTF-8"?>
But instead of easily working around that one minor issue, we’re supposed to add clutter throughout all of our code, turning
<? $something = 5; ?> <p>Something is <?=$something?></p>
<?php $something = 5; ?> <p>Something is <?php echo $something; ?></p>
The conventional wisdom is wrong and harms readability; if anything, short tags should be the standard.
(Yeah, I know it’s a non-issue if you use something like Smarty, but with short tags enabled a templating system that uses PHP itself can be just as tidy and a lot faster.)