Sunday, September 23, 2007

PHP learning--part 3

PHP syntax:



PHP code have to be put in
<?php code ?>
Example:
<?php echo 'While this is going to be parsed.'; ?>


There are 2 layer when parse a php file. First the PHP file compile with PHP parser. The output is HTML. Then the HTML output will be parse by HTML parser and then output into browser client. It is complex process behind.

When PHP parses a file, it looks for opening and closing tags, which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows php to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser. Most of the time you will see php embedded in HTML documents, as in this example.

<?php
if ($expression) {
   
?>
    <strong>This is true.</strong>
    <?php
} else {
   
?>
    <strong>This is false.</strong>
    <?php
}
?>

How this work?

I will explain:
First, when PHP parser meet first open tag <?php, it will start compile php code until it meet
close tag ?>. So the statment if ($expression) { will be put into parser. But the if statement is not completed. So it will wait until the if structure complete and output. Because the
$expression is default false, so the block: <strong>This is true.</strong> will be ignore. The compiler is enough intelligent to do this. When it meet else part, it will ouput <strong>This is false.</strong> to html parser. Then html parser will do its job: output to client browser.
Hope it is clear.

There are four different pairs of opening and closing tags which can be used in php. Two of those, <?php ?> and <script language="php"> </script>, are always available. The other two are short tags and ASP style tags, and can be turned on and off from the php.ini configuration file. As such, while some people find short tags and ASP style tags convenient, they are less portable, and generally not recommended.

Note: Also note that if you are embedding PHP within XML or XHTML you will need to use the <?php ?> tags to remain compliant with standards.

All types of php opening and closing tags:

1. <?php echo 'if you want to serve XHTML or XML documents, do like this'; ?>

2.  <script language="php">
       
echo 'some editors (like FrontPage) don\'t
              like processing instructions'
;
   
</script>

3.  <? echo 'this is the simplest, an SGML processing instruction'; ?>
    <?= expression ?> This is a shortcut for "<? echo expression ?>"

4.  <% echo 'You may optionally use ASP-style tags'; %>
    <%= $variable; # This is a shortcut for "<% echo . . ." %>

Google