Understanding the syntax of PHP is essential for anyone venturing into web development. This section provides an overview of the general PHP syntax and covers fundamental concepts.
Escaping to PHP
PHP code within a webpage can be identified by the following methods:
Canonical PHP Tags
These tags provide a clear and recommended way to embed PHP code in your files.
<?php
// PHP code goes here
?>
Short-open Tags
Short-open tags offer a concise alternative but may require specific configurations. Ensure to enable them in your php.ini file if you choose this style.
<?
// PHP code goes here
?>
ASP-like Tags
To use ASP-like tags, configure the php.ini file:
<%
// PHP code goes here
%>
Configuring php.ini allows you to use ASP-like tags. However, note that this style is less common in modern PHP development.
HTML Script Tags
You can embed PHP within HTML script tags by specifying the language attribute.
<script language="PHP">
// PHP code goes here
</script>
Commenting in PHP
PHP supports various methods for commenting code:
Single-line Comments with #
# This is a single-line comment
Single-line Comments with //
Single-line comments begin with either ‘#’ or ‘//’.
// This is also a single-line comment
Multi-line Comments with /* ... */
Multi-line comments use the /* ... */
syntax and are useful for longer explanations.
/*
This is a multi-line comment
spanning multiple lines
*/
Outputting Text in PHP
Let’s explore a simple “Hello World” example to understand different ways of outputting text in PHP
<?php
print "Hello World"; // Using print
echo "Hello World"; // Using echo
printf("Hello World"); // Using printf
?>
Why three different ways to output?
print
returns a value, always 1.echo
can take a comma-delimited list of arguments to output.printf
is a direct analog of C’s printf().