As mentioned in the previous section, the PHP script must be placed between the start tag in order for the interpreter to share the HTML and PHP codes. Even if the HTML code is not used, the indication of PHP tags is mandatory, otherwise the PHP code will be displayed in the browser window as is, without interpretation. In addition to tags, PHP supports a special type of tags for outputting the result of a single PHP statement. For example, the script in Listing 3.1 could be rewritten as shown in Listing 3.2.
Listing 3.2. Alternative tags. File shortags.php
<!DOCTYPE html> <html lang="en"> <head> <title>Alternative tags</title> <meta charset='utf-8'> </head> <body> <?= "Hello, world!"; ?> </body> </html>
As can be seen from the example above, to output the string
"Hello, world!" the
echo construction is not required, the
<?= tag automatically outputs the result to the standard stream.
It should be noted that an HTML page may contain more than one php-insert. Listing 3.3 shows an example that contains two inserts: one sets the name of the page (in the HTML
<title> tag), and the second defines the content of the page (in the HTML-tag
Listing 3.3. Multiple PHP inserts are allowed in the HTML code. Few.php file
<html> <head> <title><?php echo "Display current date" ?></title> </head> <body> <?php echo "Current date:<Ьr />"; echo date(DATE_RSS); ?> </body> </html>
If there is no output after the final tag
?>, you can omit it (Listing 3.4).
Listing 3.4. The final tag ?> Can be omitted. Missing.php file
<?php echo "Hello world!";
Moreover, the PSR-2 coding standard, which defines the formatting of the PHP code for the distributed components, requires that you do not specify the final tag ?> in all cases where this is possible.
Upon encountering a character, for example, a space, the PHP interpreter believes that the HTTP output of the document begins and the formation of the HTTP preceding header is completed. Therefore, later attempts to send the HTTP headers will fail. If the trailing tag is not used, such errors are excluded as a class.
PSR standards define the rules for developing PHP components, their purpose is to unify the frameworks and components distributed through the Composer Manager (see Chapter 26) so that the components of one framework can be used in another.
At the time of this writing, 8 standards were adopted and 9 were in preparation. You can follow the adoption of standards at http://www.php-fig.org/psr/. The PSR-1 and PSR-2 standards define the formatting and style of the PHP code. We will adhere to these standards and report formatting rules as you learn a language.