PHP Syntax
From Wiki
Contents |
PHP is whitespace insensitive
Whitespace is the stuff you type that is typically invisible on the screen, including spaces, tabs, and carriage returns (end-of-line characters). PHP's whitespace insensitivity does not mean that spaces and such never matter. In fact, they are crucial for separating the words in the PHP language. However, it means that it usually never matters how many whitespace characters you have in a row-one whitespace character is the same as many such characters. For example, each of the following PHP statements that assigns the sum of 2 + 2 to the variable $four is equivalent:
$four = 2 + 2; // single spaces $four <tab>=<tab>2<tab>+<tab>2 ; // spaces and tabs $four = 2 + 2; // multiple lines
Variables are case sensitive
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Variables are case sensitive</title>
</head>
<body>
<?php
$capital = 100;
$CaPiTaL = 200;
?>
<p><?php print("<p>Variable capital is $capital</p>");?></p>
<p><?php print("<p>Variable CaPiTaL is $CaPiTaL</p>");?></p>
</body>
</html>
The output you will see is:
Variable capital is 100 Variable CaPiTaL is 200
Statements
A statement in PHP is any expression that is followed by a semicolon (;). If expressions correspond to phrases,statements correspond to entire sentences, and the semicolon is the full stop at the end. Any sequence of valid PHP statements that is enclosed by the PHP tags is a valid PHP program. Below is a typical statement in PHP, assigning a string of characters to a variable named $greeting:
$greeting = "Welcome to PHP!";
The smallest building blocks of PHP are the indivisible tokens, such as numbers (3.14159), strings ("two"<code> or <code>'two'<code> ), variables
(such as <code>$two), constants (TRUE), and the reserved PHP words(if, else,...). These are separated from each other by whitespace and by other special characters such as parentheses ((, )) and braces ([, ]). The complex building block in PHP is the expression, which is any combination of tokens that has a value. Whenever the PHP interpreter encounters an expression in code, that expression is immediately evaluated.
Although statements cannot be combined like expressions, you can always put a sequence of statements anywhere a statement can go by enclosing them in a set of curly braces ({, }).
Comments
PHP is inspiring from several different programming languages, most notably C, Perl, and Unix shell scripts. As a result, PHP supports styles of comments from all those languages, and those styles can be intermixed freely in PHP code.
/* This is a comment in PHP */ /* This comment will /* fail on the last word of this */ sentence */ # This is a comment, and # this is the second line of the comment // This is a comment too. Each style comments only // one line so the last word of this sentence will fail too.
Variables
All variables in PHP are denoted starting with a leading dollar sign ($).
After the initial $, variable names must be composed of letters (uppercase or lowercase), digits (0–9), and underscore characters (code>_</code>). Furthermore, the first character after the $ must not be a number.
Variables can, but do not need, to be declared before assignment. Variables have no intrinsic type other than the type of their current value. In PHP, because types are associated with values rather than variables, no declaration is necessary i.e. the first step in using a variable is to assign it a value.
See also: Coding Best Practices
Assigning variables
The value of a variable is the value of its most recent assignment. Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.
Variable assignment is simple-just write the variable name, and add a single equal sign (=), then add the expression that you want to assign to that variable:
$pi = 3 + 0.14159; // approximately
Note that what is assigned is the result of evaluating the expression, not the expression itself. After the preceding statement is evaluated, there is no way to tell that the value of $pi was created by adding two numbers together.
Variables used before they are assigned have default values. There is no distinction between assigning a variable for the first time and changing its value later. This is true even if the assigned values are of different types. For example, the following code is perfectly legal:
$myNumVar = "This should be a number"; $myNumVar = 5;
If the second statement immediately follows the first one, the first statement has essentially no effect. In PHP, the default error-reporting setting allows you to use unassigned variables without errors, and PHP ensures that they have reasonable default values.
However, we recommend to declare and initialize variables before use them. Also, keep them the intended type is recommended too. These are part of the best practices recommendations.
var $age = 0; // the integer age of a person // try to keep later $age as an integer
Default Values
PHP variables do not have intrinsic type e.g. variable does not know in advance whether it will be used to store a number or a string of characters.
But how does it know what type of default value to have when it hasn't yet been assigned? The answer is that, just as with assigned variables, the type of a variable is interpreted depending on the context in which it is used. In a situation where a number is expected, a number will be produced, and this works similarly with character strings. In any context that treats a variable as a number, an unassigned variable will be evaluated as 0; in any context that expects a string value, an unassigned variable will be the empty string (the string that is zero characters long).
PHP provides a function called isset that tests a variable to see whether it has been assigned a value.
For example, running the below code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Using isset()</title>
</head>
<body>
<?php
$set_var = 0; //set_var has a value //never_set does not
print("set_var print value: $set_var<br />");
print("never_set print value: $never_set<br />");
if ($set_var == $never_set)
print("set_var is equal to never_set!<br />");
if (isset($set_var))
print("set_var is set.<br />");
else print("set_var is not set.<br />");
if (isset($never_set))
print("never_set is set.<br />");
else print("never_set is not set.");
?>
</body>
</html>
will produce the output:
set_var print value: 0 never_set print value: set_var is equal to never_set! set_var is set. never_set is not set.
The Scope of a Variable
Scope is the technical term for the rules about when a name (for, say, a variable or function) has the same meaning in two different places and in what situations two names spelled exactly the same way can actually refer to different things.
Any PHP variable not inside a function has global scope and extends throughout a given "thread" of execution. If you assign a variable near the top of a PHP file, the variable name has the same meaning for the rest of the file; and if it is not reassigned, it will have the same value as the rest of your code executes (except inside the body of functions). The assignment of a variable will not affect the value of variables with the same name in other PHP files or even in repeated uses of the same file.
In many cases you would like to hold information for longer than it takes to generate a particular Web page. For example, you can pass information from page to page using $_GET and $_POST variables, store information persistently in a database, associate it with a user's session using PHP's session mechanism, or store it on a user's hard disk via a cookie. Except inside the body of a function, variable scope in PHP is as following:
Within any given execution of a PHP file, just assign a variable, and its value will be there for you later. Variables assigned within a function are local to that function, and unless you make a special declaration in a function, that function don't have access to the global variables defined outside the function, even when they are defined in the same file.
Does variable scope persist across tags?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php $username = "John Doe";?>
<title>Scope of a variable</title>
</head>
<body>
<?php print("$username"); ?>
</body>
</html>
Should we expect our assignment to $username to survive through the second of the two PHP-tagged areas?
YES-variables persist throughout a thread of PHP execution (in other words, through the whole process of producing a Web page in response to a user's request). This is a single manifestation of a general PHP rule, which is that the only effect of the tags is to let the PHP engine know whether you want your code to be interpreted as PHP or as HTML.
Constants
Constants do not have a $ before their names, and by convention the names of constants usually are in uppercase letters.
- Constants can contain only scalar values (numbers and string).
- Constants have global scope, so they are accessible everywhere in your scripts after they have been defined-even inside functions.
NUMBER_PI = 3.14;
It is also possible to create your own constants using the define() statement, but this is more unusual than classical way. The code:
define(MY_AGE, 41);would cause
MY_AGE to evaluate to 41 everywhere it appears in your code. There is no way to change this assignment after it has been made, and like variables, constants that are not part of PHP itself do not persist across pages unless they are explicitly passed to a new page. The usual way is to define the constants in an external include file.
