PHP - Function Global Variables

Introduction

In PHP, all variables created outside a function are, in a sense, global.

They can be accessed by any other code in the script that's not inside a function.

To use such a variable inside a function, write the word global followed by the variable name inside the function's code block.

Demo

<?php

         $myGlobal ="Hello there!";

         function hello() {
           global $myGlobal;
           echo"$myGlobal \n";
         }//from  w w w  .  ja va 2  s  . c o  m

         hello(); // Displays"Hello there!"
?>

Result

You don't need to have created a variable outside a function to use it as a global variable.

Demo

<?php
         function setup() {
           global $myGlobal;
           $myGlobal ="Hello there!";
         }//from  www . j  ava2  s . c  om

         function hello() {
           global $myGlobal;
           echo"$myGlobal \n";
         }

         setup();
         hello(); // Displays"Hello there!"
?>

Result

You can also declare more than one global variable at once on the same line - just separate the variables using commas:

function myFunction() {
           global $oneGlobal, $anotherGlobal;
}

You can access global variables using the $GLOBALS array.

This array is a superglobal, which means you can access it from anywhere without using the global statement.

It contains a list of all global variables, with the variable names stored in its keys and the variables' values stored in its values.

Demo

<?php

          $myGlobal ="Hello there!";

          function hello() {
           echo $GLOBALS["myGlobal"]."\n";
          }//from  www  .j a  va  2s.c  om

         hello(); // Displays"Hello there!"
?>

Result