Skip to main content

How to Define and Use Global Variables in PHP

A global variable is a variable that is accessible from any function in a PHP script. You can create a global variable by defining it outside of any function, or you can declare it as global inside a function.

We can define and use global variables in PHP function by using the “global” keyword.

$x = 5; // Define a global variable

function myTest() {
    global $x; // Use the global variable $x inside the function
    echo "<p>Variable x inside function is: $x</p>";
} 

myTest(); // Call the function

Another way is to use the array $GLOBALS[variable_name]. $GLOBALS is a superglobal variable which is used to access global variables from anywhere in the PHP script.

$x = 5;
$y = 10;

function sum() {
    $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
} 

sum();

echo $y; // Outputs 15

By continuing to use the site, you agree to the use of cookies.