PHP Variable Scope

In PHP any where you can create variables. Scope of a Variable is the part of the script where the variable can be referenced/used.

PHP has 3 different level scope variables

  • Local
  • Global
  • Static

Global vs Local Scope

A Variable declared outside of function has a global scope. and can be accessed outside of a function.

A Variable declared with in a function has a local scope. which can onle be used with in a function.


<?php

$a=10; //Global Variable

function ShowUsers(){
	$a=5; //Local Scope
	echo "Total Users are $a <br/>";
}

ShowUsers();
echo $a;
?>
	

Now we created two $a variables but both contains own values why ? because $a which is created outside of function is accessible to every where except functions. and other $a is created inside function which is only accessible with in a function.

PHP GLOBAL Keyword

In PHP we use GLOBAL Keyword before variable name when we want to access variable every where.


<?php
$a=10; 
$b=20;
function ShowUsers(){
	GLOBAL $a,$b
	$a+=$b;
}

ShowUsers();
echo $a;// output will show 30
?>
	

PHP STATIC Keyword

Normally when a function complete it's execution it's variable are deleted. however some times are required to preserve some local variables to save for further use.

To do this we use STATIC Keyword before variable name


<?php

function Counter(){
	STATIC $a=0; //Static Variable
	echo $a;
	++$a;
}

Counter(); // it will output 0
Counter(); // it will output 1
Counter(); // it will output 2
?>