PHP Global Variable


 

PHP Global Variable

PHP Global Variable, In this tutorial gives you an idea about accessing global variables, it provides two ways to access global variable one is global keyword and $GLOBALS associative array.

PHP Global Variable, In this tutorial gives you an idea about accessing global variables, it provides two ways to access global variable one is global keyword and $GLOBALS associative array.

PHP  Global Variable

To access global variable in PHP we need to use global keyword or $GLOBALS associative array

global is a keyword which helps us to access the globally declared variable. There is no limit to use global keyword within a program.

$GLOBALS is an associative array containing references to all global variables, the variable names are the keys of the array.

Code for PHP Global Variable:

<?php

$a=1;

function globe()

{

$a="12";

echo "Value of a is:".$a;

echo "<br />";

global $a;//global keyword helps us to access globally declared variables

echo "Value of a is :".$a;

echo "<br> Other way to access global variable";

echo " <Br>Value of a is :".$GLOBALS["a"];//using $GLOBALS associative array.

}

globe();

?>

Output:

Value of a is:12
Value of a is :1
Other way to access global variable 
Value of a is :1

Ads