Declare a global variable in PHP
This article demonstrates how to declare a global variable in PHP.
1. Using $GLOBALS variable
The recommended solution to declare a global variable is to use the $GLOBALS super variable, which is an associative array of all variables defined in the global scope. You can add your variables to the $GLOBALS super variable and use it like follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php function initialize_globals() { $GLOBALS["OK"] = 200; $GLOBALS["CREATED"] = 201; $GLOBALS["ACCEPTED"] = 202; $GLOBALS["BAD_REQUEST"] = 400; $GLOBALS["UNAUTHORIZED"] = 401; $GLOBALS["FORBIDDEN"] = 403; } initialize_globals(); echo $GLOBALS['OK']; // 200 ?> |
Note that if a variable is declared outside a function, it has a global scope. In other words, you can access a global variable within a function using the global keyword or access it using the $GLOBALS super global array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php $success = 200; function foo() { global $success; echo $success, PHP_EOL; } function bar() { echo $GLOBALS['success'], PHP_EOL; } foo(); // 200 bar(); // 200 ?> |
2. Using class
Alternatively, you can create a Globals class containing references to all variables. A typical implementation of the Globals class would look like below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php class Globals { static $OK = 200; static $CREATED = 201; static $ACCEPTED = 202; static $BAD_REQUEST = 400; static $UNAUTHORIZED = 401; static $FORBIDDEN = 403; } echo Globals::$OK; // 200 ?> |
3. Using define() function
Finally, you can use the define() function to define named constants that are accessible throughout the script. The advantage of using this method over all the others is that the constant value cannot be modified once it has been created. The following example provides an illustration.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php define("OK", 200); define("CREATED", 201); define("ACCEPTED", 202); define("BAD_REQUEST", 400); define("UNAUTHORIZED", 401); define("FORBIDDEN", 403); echo OK; // 200 ?> |
That’s all there is to declaring a global variable in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)