2.6.6 Opening and closing code islandsThis is NOT the latest copy of this book; click here for the latest version.
There are many ways to open a PHP code island (to enter PHP parsing mode), and you are welcome to choose which you prefer. The most common (and recommended) manner is to use <?php to enter PHP mode, and ?> to leave PHP mode, however you can also use the short tags version, <? and ?>.
The short version has one big advantage and one big disadvantage. The advantage is that you can output information from your script by using a special short tags hack, <?=. Here is how that looks:
<?="Hello, world!" ?>
Here is the equivalent written using the standard open and closing tags:
<?php
print "Hello, world!"; ?>
As you can see, the short tags version is much shorter, if a little harder to read. However, the big downside to the short version is that it clashes with XML, which also uses <? to open code blocks. This means that if you try to use XML and short-tagged PHP together, you'll almost certainly encounter problems - this is the primary reason people recommend using the normal open and close tags.
Two other, lesser-used variants exist: <% %>, which opens and closes code blocks in the same way as Microsoft's ASP, and also <script language="php"></script>. These two often work better with visual editor programs such as Dreamweaver and FrontPage, however they are not recommended for general use because they need to be enabled to work.
You can switch into and out of PHP mode by using <?php and ?> whenever you want to and as often as you want to.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|