In PHP when a variable is defined it is available only to the extend that is defined for and not beyond that. This will make life easier for you if you don’t want to unset() every variable that you make(but still a good idea to do it) and it also allows you to define the same name for variable in different part of the code and store different values and even data types in them also it will allow you to transfer information between different parts of your code like different functions, pages etc.

The part of the code that a variable is available for is the Scope of a variable. There are two kind of variables:

  • Local variables

These are the variables only available to a small part of the script or only to one page. You don’t have to define a local variable as every variable set in PHP unless it has been set to be Global is automatically local.

These are variables available in every part of the code and in every page in your script.

To explain the differences and how to use global and local variables I need to show you some examples:

First for local

<?php

$a=1;

echo $a;// this will show 1 as output as $a is a local to this script

?>

or

<?php

$a=1;

$b=2;

function adding(){

$a=2;

$b=3;

return($a+$b);//$a and $b are local variables here

}

echo adding();// this will show 5 and not 3 as $a in the function is 2 and $b in the function is 3 because they are local to that function.

?>

No for global, What if you wanted the result of the above script be 3 here is how:

<?php

$a=1;

$b=2;

function adding(){

global $a,$b;// access $a and $b from the global scope

return($a+$b);

}

echo adding();// This time it will show 3

?>

You can also use $GLOBALS array to access them, $GLOBALS is an internal array available to all scopes so you don’t need to tell the script to access them. It is an associative array:

<?php

$a=1;   $b=2;

function adding(){

return($GLOBALS[‘a’]+$GLOBALS[‘b’]);

}

echo adding();// this will show 3

?>

There are other internal global array available in PHP but for this PHP Tutorial $GLOBALS will do.

To read more about Global variables and how to use them securely and more importantly correctly read “Why Global Variables in PHP is Bad Programming Practice” if it is done badly that is(It’s a bit more advanced).

%d bloggers like this: