The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:
<?php $a = 1; include ‘b.inc’; ?> |
Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope.
There are 3 type of scopes of variable are there…
- Local – variables which declared inside of a function
- Global – variables which declared outside of the function
- static
- Global scope
Variable $val declared as globally, it’s mean that variable can be accessed outside of function, not inside a function.
File – glocalScope.php
<?php error_reporting(0); $val=’ratan tata’; function dis(){ echo ‘name is(inside function): ‘.$val; } dis(); echo ‘<br>’; echo ‘name is(outside function): ‘.$val; ?> |

- Local scope
Now, the variable $val declared as locally, it’s mean that variable can be accessed only inside that function, not outside of that function. Let’s understand through below code…
File – localScope.php
<?php error_reporting(0); function dis(){ $val=’ratan tata’; echo ‘name is(inside function): ‘.$val; } dis(); echo ‘<br>name is(outside function): ‘.$val; ?> |

- Static scope
Let’s see a code, without static scope.What happened if we don’t we keyword ‘static’.
File – without_staticScope.php
<?php function incr(){ $a=0; echo “<br> a is: “.$a; $a++; } incr(); incr(); incr(); ?> |

Let’s see a code, with static scope from the upper code. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.
File – with_staticScope.php
<?php function incr(){ static $a=0; echo “<br> a is: “.$a; $a++; } incr(); incr(); incr(); ?> |

- Global keyword
By declaring global keyword before variables, within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.
File – withGlobal1.php
<?php $name=’microcodes’; $phone=9330; function run(){ global $name,$phone; echo “<br> inside function, name is: $name”; echo “<br> inside function, phone is: $phone”; } run(); echo “<br> outside function, name is: $name”; echo “<br> outside function, phone is: $phone”; ?> |
