| Viewed 436 times

PHP how to make a global variable


PHP how to make a global variable

PHP
Loading...
1 Answer
Mohammad Qandeel
Answered
11

At first, I will explain to you the PHP variable scope 

variable scope is the place where you can access the variable so, if you initialize variable inside the variable scope you can`t access it from outside 

Example 

<?php
$var_in_global_scope = 1;  

function test_var()
{ //start function test_var scope

    echo $var_in_global_scope ; //Undefined variable-- cannot access var from outside scope

}  //end function test_var scope

test_var(); //make error Undefined variable
?>

Output

Notice: Undefined variable: var_in_global_scope 

To access the variable from another scope we use superglobal variables $GLOBALS

Example 

<?php
$var_in_global_scope  = 1; /* global scope */ 

function test()
{ 
    echo $GLOBALS['var_in_global_scope '];  
} 

test();
?>

Output

1

 

List of PHP super global variables :

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


Related Questions