SHARE

What is Global Variable in PHP (SuperGloblas)

As show their name “Global” . In PHP , Global variables are pre-defined variable that are accessible from anywhere in php file . Global variable works like simple variable but a big difference between it,  accessibility of it . SuperGlobals or globals are very useful in php programming . Developer can access these with less effort .

PHP global variables are also know as SuperGlobals. Before learn about Global variable ,learn what is variable .

Syntax

Just like simple php variables ,globlas are also started “$” sign .  But After that variable name . In  globals , name of variable is pre-defined and case sensitive . Only capital letters are allowed .

For example syntax is:

$GLOBLAS[' '];

Pre-defined Global variables

  • $GLOBALS
  • $_SERVER
  • $_REQUEST
  • $_POST
  • $_GET
  • $_FILES
  • $_ENV
  • $_COOKIE
  • $_SESSION

Uses And Benefits

In the following php code Three variables are created “num1 , num2 , num3” . These are simple variables .

Test Following Code

<?php
$num1 = 5;
$num2 = 10;
function sum(){
$num3 = $num1 +$num2;
}
sum();
echo "Sum of numbers".$num3;
?>

When you try to use these variables inside the function ,it give error that variables are not defined . Reason is, num1 and num2 are declared out side of the function , so function can’t access these variables value.

In this condition Globals or SuperGlobals are used .

Example

<?php
$num1 = 5;
$num2 = 10;
function sum(){
$GLOBALS['num3'] = $GLOBALS['num1'] + $GLOBALS['num2'];
}
sum();
echo "Sum of numbers".$num3;
?>

Test This Code

In this code all ,variables defined as global ,so user can access or use these variable anywhere in file . When user call the global variable it bypass all of the codes and get accessed .

Example

<?php $num1 = 5; $num2 = 10;
?>
<div> This div is in between the declared and function </div>
<?php
function sum(){
$GLOBALS['num3'] = $GLOBALS['num1'] + $GLOBALS['num2'];
}
?>
<?php
sum();
echo "Sum of numbers".$num3;
?>

In this code ,Global variable is declared in one php tag and called in other php tag . Some html code and text are placed in between the code ,but still variable is accessible .This is a feature of PHP Globals or global variables .

In you need more help then see the following video

Video