Escaping to PHP
The PHP parsing engine needs a way to differentiate PHP code from other elements
in the page. The mechanism for doing so is known as ‘escaping to PHP.’
There are four ways to do this:
• Default tags
• Short tags
• Script tags
• ASP-style tags
Default Tags
The default tags are perhaps those most commonly used by PHP programmers,
due to clarity and convenience of use:
These tags may also be the most practical ones because the initial escape
characters are followed by php, which explicitly makes reference to the type of
code that follows. This can be useful because you may be simultaneously using
An Introduction to PHP
23
several technologies in the same page, such as JavaScript, server-side includes,
and PHP. Any ensuing PHP code will then follow the initial escape sequence, preceded
by the closing escape sequence, "?>".
Short Tags
The short tag style is the shortest available for escaping to PHP code:
Short tags must be enabled in order for them to work. There are two ways to
do this:
• Include the —enable-short-tags option when compiling PHP.
• Enable the short_open_tag configuration directive found within the php.ini
file.
Script Tags
Several text editors will mistakenly interpret PHP code as HTML (that is, viewable)
code, interfering with the Web page development process. To eliminate this
problem, use the following escape tags:
ASP-Style Tags
Chapter 1
24
A fourth and final way to embed PHP code is through the use of ASP (Active
Server Page)-style tags. This way is much like the short tag way just described,
except that a percentage sign (%) is used instead of a question mark.
<% print "Welcome to the world of PHP!"; %>
A variation of the ASP-style tag that can result in a lesser degree of code clutter
is available. This variation eliminates the need to include a ‘print’ statement in
the enclosed PHP code. The equals sign (=) immediately following the opening
ASP tag signals the PHP parser to output the value of the variable:
<%= $variable %>
Making use of this convenient tag style, we could execute the following:
<%
// set variable $recipe to something…
$recipe = "Lasagna";
%>
Luigi’s favorite recipe is <%=$recipe;%>
There are actually two separate PHP scripts in this listing. The first assigns the
value “Lasagna” to the variable $recipe. Later on, when it is necessary to display
the value of the variable $recipe, you can use the ASP-style variation for this sole
purpose. Incidentally, you could also use short tags () in much the same
way.
No comments:
Post a Comment