The Global Keyword

A global variable can be accessed in any part of the program. In php global keyword is used to access a global variable. Global keyword has to use before the variables (inside the function).

Global variables are stored in an array called $GLOBALS[index]. Index holds the name of variable and this array can directly access with functions.

Example :

<?php
$a = 1;
$b = 4;
function sum()
{
global $a;
global $b;
echo “value of a is ”.$a;
echo “value of b is “.$b;
$a = $a+$b;
}
sum();
echo “Sum = ”.$a;
? >

Output:
Sum = 5

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.