PHP Variables
The value of data is permanent but the value of the variable which can be changed during programming is called a variable.
The variable is used to store data in a programming language. Some rules have been made to name the variable, which is as follows:
Rules For PHP Variables:
- Variable names are defined using the "$" sign.
- While giving the name of the variable, the first letter should not be a number, that is, English letters or underscore () can be the symbol only.
- The next character should also not contain space, or any symbol except underscore (_).
- A variable names can be of any number of letters.
- Reserve words called keywords cannot be used in variable names.
Example:
The equal sign '=' is used to assign a value to a variable.
<?php $a=5; $b=10; echo "Value of a= $a <br> Value of b = $b"; ?>
Output:
Value of a= 5
Value of b = 10
Read Also - PHP Echo and Print Statements | PHP Tutorial
PHP Scope
In Scope, we determine the extent of making the variable available, if it was a global variable, it can be used everywhere and in the case of local only up to a certain extent. Variables can be declared in PHP in the following 3 ways:
- Local Variable
- Global Variable
- Function Parameters
1) Local Variable:
If the variable is defined under the same scope then it is called local variable. This type of variable is accessed only within the same scope/function:
Example:
<?php $a = 5; //global variable function fun1() { $a = 10; //local variable echo $GLOBALS['a']; //display global variable } fun1(); ?>
Output: 5
2) Global Variable:
If the variable is defined outside any scope/function then it is called a global variable.
Its advantage is that it can be used in any scope/function for which the $GLOBALS keyword has to be used. To understand this, see the following example:
Example:
<?php $pi=3.14; //global variable function area() { $r=4; //local variable echo 'Area of Circle is:'. $GLOBALS['pi']*$r*$r; } function circum() { $r=4; echo'<br> Circumference of Circle is:' . $GLOBALS['pi']*$r*2; } area (); circum(); ?>
Output:
Area of Circle is:50.24
Circumference of Circle is:25.12
Read Also - PHP Comments
3) Function Parameters:
Variable can also be used as a parameter of a function. In the above program, function named area and circum have been taken, if we write any variable under their brackets then it is called function parameters.
The value of this type of variable can be given globally while calling the function but it is used only within the local function. This can be understood by changing the above example as follows:
Example:
<?php $pi=3.14; //global variable function area ($r) { echo 'Area of Circle is:'. $GLOBALS['pi']*$r*$r; } function circum ($r) { echo '<br> Circumference of Circle is:' . $GLOBALS['pi']*$r*2; } area (4); circum(5); ?>
Output:
Area of Circle is:50.24
Circumference of Circle is:31.4
One parameter has been taken in both the functions of the above program.
0 Comments