PHP Tutorial – Syntax
In this tutorial you will learn about PHP Syntax – Syntax for Writing a script, Scripts VS. File and Comments
Writing a script:
To embed PHP code inside a file, it has to be inside a special set of opening and closing tags.
PHP supports the following tags sets:
1. Opening (< ?php) and closing (? >)
2. Opening (< ?) and closing (? >)
3. Opening (< %) and closing (% >)
4. Opening (< script language=”php” >) and closing (< /script >)
Example:
< html >
…..< head >
……….< title >Sample document< /title >
…..< /head >
…..< body >
……….< ?php
……………echo “Sample text”;
……….? >
…..< /body >
< /html >
The text inside the PHP tags has to be interpreted to generate the HTML equivalent before sending to the browser, anything outside the PHP tags is not interpreted.
Opening and closing tags can be mixed, for example, < % echo “Text” ? >
PHP file can have as many as PHP scripts inside the HTML code.
< ?= ? > tags:
It’s used to output the embedded script value, the expression will be evaluated, and it’s value will be sent to the browser.
Example:
< ?= “PHP is easy to learn” ? >
Scripts VS. File:
A script may include many files, this enables PHP coders to write some of the code once, and use it in many scripts, to include an external file into your script, you can use one of the following:
1. include: reads the external file, and interprets it, if the external file can’t be found, a warning is produced, and the execution continues.
2. require: the same as includes, but it causes the execution to stop.
3. include_once: works the same way as include, but the included file will be interpreted just once, at the first time it’s included, if it’s included again in the same file, it won’t be interpreted again.
4. require_once: the same as require, but also interpreted once like include_once.
Example:
The following script is saved as included.php:
< ?php
…..echo “I’m included”;
? >
The following script will include the file included.php:
< ?php
…..include “included.php”;
…..echo “I included a file”;
? >
Both files have to be in the same directory.
Comments:
A comment is a portion of program that’s only used for PHP code writers, it comments the code so other programmers can easily understand the code when they read it, also it makes it easy for you to figure out what you wrote when you use the code later.
Comments are stripped out when a PHP script is interpreted.
There are many kinds of comments in PHP:
• C-style multiline comments: starts with /* and ends with */, for example:
/* This is
a c-style
comment */
• Single line comments: starts with # or //, for example:
// This is a one line comment
# This is another one line comment.