Home Tutorial Php PHP Variable Global

 
 

Share on Google+Share on Google+
PHP Variable Global
Posted on: January 14, 2010 at 12:00 AM
Advertisement
PHP Global variable are the variables which can be used anywhere in the program. It is used to store the value inputted by the user.

PHP Global Variables

PHP Global variable are the variables which can be used anywhere in the program. It is used to store the value inputted by the user. We can use global variable in different-different ways, For example :

PHP Global Variable Example 1:

  

<?php

$num1 = "5";

$num2 = "6";

function multi()

{

global $num1,$num2;

$num2 = $num1*$num2;

}

multi();

echo $num2;

?>

The output of the above example is : 30

In the above example, we declared two local variables:  $num1 and $num2. In the next line, we defined the function multi() and within function  the first line referred to the global variable. Here, we declared $num1 and $num2 as global variable. It means, all references to either variable will refer to the global version. You can declared unlimited numbers of global variable that can be controlled by a function.

 

PHP Global Variable Example 2 :

<?php

$num1 = "5";

$num2 = "6";

 

function multi()

{

$GLOBALS['num2'] = $GLOBALS['num1']*$GLOBALS['num2'];

}

multi();

echo $num2;

?>

The output of the above example is : 30

The second method to access the global variable is to use predefined $GLOBALS array within the PHP. $GLOBALS array is an associative array that containing a reference to every individual variable which is currently available in the global scope of the script. It means it can be accessed easily anywhere in the code. I suppose, this is hardly use in your script.

 

Example 3 :

<?php

function universal()

{

$test = "Inside the function!";

echo "This is a variable : ".$GLOBALS['test']."<br/>";

echo "This is a variable : ".$test."<br/>";

}

$test = "Outside the function!";

universal();

?>

The output of the above example is : This is a variable : Outside the function!
                                                        This is a variable : Inside the function!

In the above example, we used $test variable twice in the code to initialized the value. The first $test variable inside the function refers that it is a local variable and we can used that variable only within the function or curly braces. The second $test variable outside the function refers that it is a global variable and we used that variable within the function by mentioning $GLOBALS['test']. GLOBAL variable can be used anywhere in the program.

 

Advertisement

Related Tags for PHP Variable Global:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 14, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com