Learn About Global Variables in PHP

Learn About Global Variables in PHP

  • PHP
  • 3 mins read

In this tutorial, you will learn about global variables in PHP. Topics covered like what is the scope of a global variable, how to access a global variable and how to use global variables in the PHP program.

What is $GLOBALS[index] in PHP?

In PHP, an array named $GLOBALS[index] is the source of all global variables. Here the index will hold the name of the variable. This array is accessible inside a function.

Here is a PHP program for using a global variable ($a) in an array inside a function f1:

<html>
    <body>
        <?php
$a="Kolkata is the capital of West Bengal"; //global scope
function f1()
{
    $GLOBALS['a']="We know it"; //updating value of global variable
}
f1(); //function calling
echo $a; //accessing updated value of global variable outside the function
        ?>
    </body>
</html>

Output

We know it

This program is containing a global variable $a, which you can access by specifying array $GLOBALS['a']. Here the value of the global variable is changing inside the function body. After the function call, the new updated value of $a will display.

What is the Scope of a Global Variable in PHP?

When a variable is declared outside a function, then that variable will contain global scope. We can access that variable only outside that function.

Now we are writing a program on the global scope of a variable. In this program, we are declaring a variable outside a function f1, and we are trying to access that variable within the function:

<html>
    <body>
        <?php
$a="This is India"; //global scope
function f1()
{
    echo $a; //trying to access variable within the function body,error beacuse $a is a global variable
}
f1(); //function calling
        ?>
    </body>
</html>

Output

E_NOTICE : type 8 -- Undefined variable: a -- at line 7

This program will contain an error because the variable $a has a global scope, and it is accessing within the function body.

How to Access a Global Variable Within a Function in PHP?

PHP supports a keyword global which is used to access the global variable within a function. When we want to access the global variable within a function, we will use the keyword global before the variable within that function.

Now we will write a program for accessing a global variable $a within a function f1:

<html>
    <body>
        <?php
$a="Mango is green"; //global scope
function f1()
{
    global $a; //accessing global variable $a through global keyword
    echo $a; 
}
f1(); //function calling
        ?>
    </body>
</html>

Output

Mango is green

This program is containing a global variable $a, and we are accessing that variable inside the function using the keyword global and printing the value of that global variable. After executing the function, we will get the result as "Mango is green.".