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'];


echo $y; // Outputs 15

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

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.