Home >Backend Development >PHP Tutorial >How Can I Access a Global Variable in All PHP Functions Without Repeatedly Declaring it?
Global Variable Declaration in PHP
Problem:
In a PHP script, it is necessary to declare a variable as global inside each function that needs to access it. Is there a way to define a global variable once and access it in all functions simultaneously without manually using global within each function?
Answer:
There are two alternative methods:
Method 1: Using the $GLOBALS Array:
The $GLOBALS array is an associative array that contains references to all variables defined in the global scope. To declare a global variable using $GLOBALS, simply assign it a value outside of any function:
$GLOBALS['a'] = 'localhost';
Once defined, you can access $GLOBALS['a'] in any function:
function body() { echo $GLOBALS['a']; }
Method 2: Using a Class with Properties:
If functions share a set of variables, consider encapsulating them in a class with properties:
class MyTest { protected $a; public function __construct($a) { $this->a = $a; } public function head() { echo $this->a; } public function footer() { echo $this->a; } }
Instantiate the class outside of any function and access its properties within the methods:
$a = 'localhost'; $obj = new MyTest($a);
The above is the detailed content of How Can I Access a Global Variable in All PHP Functions Without Repeatedly Declaring it?. For more information, please follow other related articles on the PHP Chinese website!