Google News
logo
PHP Program to $GLOBAL - Used to access global variables from anywhere in the PHP script
In the following example of PHP program that demonstrates how to use the `$GLOBALS` array to access global variables from anywhere in a PHP script :
Program :
<?php

// Define a global variable
$global_var = "Hello, world!";

// Define a function that uses the global variable
function print_global_var() {
    echo $GLOBALS["global_var"];
}

// Call the function
print_global_var();

?>
Output :
Hello, world!
In the above example, we have defined a global variable `$global_var` and a function `print_global_var()` that uses the variable. Inside the function, we use the `$GLOBALS` array to access the global variable `$global_var`.

The `$GLOBALS` array is a special associative array provided by PHP that contains references to all variables that are currently defined in the global scope. This means that you can use the `$GLOBALS` array to access any global variable from within a function or a class method, without having to pass it as an argument or declare it as a global variable inside the function.

Note that using global variables can sometimes make your code harder to understand and maintain, especially in larger projects. It is generally recommended to avoid using global variables whenever possible and instead use function parameters, return values, or object properties to pass data between functions and modules.