Variables in PHP
A variable is a named location in computer’s memory. It is used to store data temporary during execution of a script.
One of the important characteristic of variable is that the value of the variable may change during execution of the script.
The general syntax for declaring variable is given below:
$ VariableName =value;
$Number1 = 10;
Once variable is declared you can refer it anywhere in the script just by using its name along with $ sign.
While declaring variables you must follows the following rules:
(1) Variable name can contain letters, digits and underscore symbol.
(2) It can not start with digits.
(3) Yu can not use white spaces in the name of the variable.
(4) Uppercase and Lowercase letters are distinct.
There is no need to specify data type for the variable. It will automatically determine its type base on the value that is stored in it. This is because PHP is known as loosely typed language.
PHP is known as a loosely - typed language because It converts a variable’s data type automatically, depending on the context in which the variable is used. For example, you can initialize a variable with an integer value then you can add a float value to it, thereby turning it into a float value and then join it onto a string value to produce a longer string.
Constant in PHP
Constant means fixed value. One of the most important characteristic of constant is that once the value of constant is defined it can not change during the execution of script.
In PHP you can define constant using define () function.
The general syntax for defining constant is given below:
define (“ConstantName” ,value);
define (“PI”, 3.14);
However it is not mandatory to write constants in upper case, but generally programmer prefer to write them in upper case to distinguish them from variables.
You can refer to the constant in a script just by using its name. There is no need to use $ sign.
Consider following rules while defining constants:
(1) Name of the constant can start with letters or underscore symbol, but it can not starts with digit.
(2) Uppercase and lowercase letters are distinct because constant is case sensitive.
(3) You must assign value to the constant at the time of defining it.
(4) Write constants in uppercase letters to distinguish them from variables.
Consider Following Example:
$r = 3;
$area = PI * $r * $r;
echo "Area of Circle with radius $r is $area";
Area of Circle with radius 3 is 28.26