Example of PHP variable:
$fruit = “apple”; //character type variable
$x=10; //integer type variable
There are four scopes of PHP variable.
- Local – Its scope for the block in which it is declared, it can’t be accessed outside of that block.
- Global – Its scope for the whole code, it can be accessed from any part of the PHP file.
- Static – It contain the value till end of the execution of the file.
- Parameter – Its scope is limited to particular function parameters.
Example of scope of variable:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| $a = 10; // global variable$b = 20; // global variablefunction Sum(){ global $a,$b; // accessing global variables using 'global' keyword $c = $a + $b; echo $c; // local variable}function varStatic(){ static $d = 0; // static variable echo $d; $d++;}Sum();echo $b;varStatic(); |
In varStatic() function, it will initialize $d=0 only when the function called for the first time and it will increment the value of $d every time function called.
No comments:
Post a Comment