Search This Blog

5/20/2011

PHP Delimiter

Introduction

PHP is an HTML embedded language. This means the PHP code can be inside an HTML, but should have one way to determine whether a stretch of code is PHP or HTML. The way is the use of PHP delimiters. The PHP interpreter is applicable to the stretch of code delimited by the PHP delimiters.

Some programmers use PHP code delimiters, but they do not know about their nuances. Let's see them at this post.


Delimiter

There are diferent PHP code delimiters. The most common is the clasic <?php ... ?>.

There are also:

  • <? ... ?> is an abbreviated way
  • <script language="php">...</script> JavaScript like way
  • <% ... %> ASP way

And some shortcuts:

  • <?= ... ?> is shortcut of <? echo ... ?>
  • <%= ... %> is shortcut of <% echo ... %>

The "short_open_tag" PHP directive must be enabled to use the shortcuts. Some PHP versions do not allow programmers to switch this directive with ini_set function. So, the use of the shortcut is not recomended for applications that may be distributed or installed in servers that you do not have access to PHP configurations.

To use ASP notation is the same history. You need to activate "asp_tags" PHP directive, that is not always avaliable to be switched by programmers.

And the JavaScript notation is very long and inconvenient. The unique advantage I see in this notation is to create a PHP code that can be parsed as an XML. The <script> would be considered a tag, as any other. The problem is the code should not have special characters, like <, > or & (with risk the XML to get invalid).

I recomend the classic way, because it independs of configuration.


Optional PHP closing tag

The PHP closing tag (?>) is optional. Yes, it is! Many programmers do not know, but it is not necessary to close PHP code if, after it, there are not any code nor text. This is useful to avoid the existence of extra spaces after the PHP closing tag. If you have a code with spaces (or new lines) after a PHP closing tag, then the functions that send HTTP headers do not work (for example setcookie or header functions). This ocurrs becaus HTTP headers can be sent only if no content has been sent yet (including spaces and new lines).


PHP closing tag has an instruction delimiter

Other information that not everyone knows is that the PHP closing tag embeds an instruction delimiter (semicolon). It means that before ?>, normally you do not need to put ";".

Example of valid code:

<?php echo 'a' ?><?php echo 'b' ?>

You have to worry about it when you use heredoc or nowdoc notation.

The code bellow is invalid:

<?php
echo <<<TEXT
hi
TEXT ?>

In this case, heredoc or nowdoc closing string have to be alone in the line. So, the PHP closing tag can be in the next line.

<?php
echo <<<TEXT
hi
TEXT
?>

No comments:

Post a Comment