PHP Tags
As PHP can be HTML-embedded, commonly your PHP code would be interspersed within a page's HTML. The most important syntactical rule is that all PHP code goes between the opening and closing PHP tags:
<?php ?>
The <?php and ?> are the formal PHP tags. Old versions of PHP did also support short tags <? and ?> and ASP-compatible tags <% and %> . However, it is recommended that you always use the formal tags (in particular, the short tags conflict with XML).
Assuming that you've created a plain-text file with a valid file extension and that you're running it on a PHP-enabled computer (or within NuSphere's PhpED), anything within the PHP tags will be handled by the PHP parser, anything outside of the PHP tags will be sent to the Web browser as standard HTML.
Statements, Structures, and Comments
The rest of the PHP syntax can be broken down into statements, structures, and comments. Every statement in PHP must conclude with a semicolon (;). A statement, in layman's terms, is an executed action: the assignment of a value to a variable, the invocation of a function, and so on. These are all statements:
$var = 45;
echo 'Print this.';
$var = number_format($var, 2);
Failure to conclude a statement with a semicolon results in a parse error.
Structures are blocks that encapsulate statements. In PHP, structures include:
Structures use the curly braces—{ and }— to indicate the start and end of the structure. Some structures, like conditionals in certain circumstances, do not require the curly braces, although omitting them can lead to confusion and errors.
Syntactically, it makes no difference where the opening and closing braces are placed. Both of these common styles are valid:
if (true) {
// Do this.
}
if (true)
{
// Do this.
}
PHP supports three styles of comments. To have a single-line comment use # or //:
# This is a comment.
// Some comment.
$var = 'value'; // Another comment.
Anything after the comment character to the end of the line will not be executed. As in the last example above, you can also place comments after some executed PHP code.
To create multi-line comments, use /* and */:
/* This is
a multi-line
comment. */
Anything between the opening and closing comment tags will not be executed. For debugging purposes, the multi-line comment can also be used to render large blocks of code inert.
|