create superglobal variables in php?
PhpPhp Problem Overview
is there a way to create my own custom superglobal variables like $_POST and $_GET?
Php Solutions
Solution 1 - Php
Static class variables can be referenced globally, e.g.:
class myGlobals {
static $myVariable;
}
function a() {
print myGlobals::$myVariable;
}
Solution 2 - Php
Yes, it is possible, but not with the so-called "core" PHP functionalities. You have to install an extension called runkit7: Installation
After that, you can set your custom superglobals in php.ini as documented here: ini.runkit.superglobal
Solution 3 - Php
I think you already have it - every variable you create in global space can be accessed using the $GLOBALS
superglobal like this:
// in global space
$myVar = "hello";
// inside a function
function foo() {
echo $GLOBALS['myVar'];
}
Solution 4 - Php
Class Registry {
private $vars = array();
public function __set($index, $value){$this->vars[$index] = $value;}
public function __get($index){return $this->vars[$index];}
}
$registry = new Registry;
function _REGISTRY(){
global $registry;
return $registry;
}
_REGISTRY()->sampleArray=array(1,2,'red','white');
//_REGISTRY()->someOtherClassName = new className;
//_REGISTRY()->someOtherClassName->dosomething();
class sampleClass {
public function sampleMethod(){
print_r(_REGISTRY()->sampleArray); echo '<br/>';
_REGISTRY()->sampleVar='value';
echo _REGISTRY()->sampleVar.'<br/>';
}
}
$whatever = new sampleClass;
$whatever->sampleMethod();
Solution 5 - Php
One other way to get around this issue is to use a static class method or variable.
For example:
class myGlobals {
public static $myVariable;
}
Then, in your functions you can simply refer to your global variable like this:
function Test()
{
echo myGlobals::$myVariable;
}
Not as clean as some other languages, but at least you don't have to keep declaring it global all the time.
Solution 6 - Php
No
There are only built-in superglobals listed in this manual
Solution 7 - Php
Not really. though you can just abuse the ones that are there if you don't mind the ugliness of it.
Solution 8 - Php
You can also use the Environment variables of the server, and access these in PHP This is a good way to maybe store global database access if you own and exclusively use the server.
Solution 9 - Php
possible workaround with $GLOBALS
:
file.php:
$GLOBALS['xyz'] = "hello";
any_included_file.php:
echo $GLOBALS['xyz'];
Solution 10 - Php
One solution is to create your superglobal variable in a separate php file and then auto load that file with every php call using the auto_prepend_file
directive.
something like this should work after restarting your php server (your ini file location might be different):
/usr/local/etc/php/conf.d/load-my-custom-superglobals.ini
auto_prepend_file=/var/www/html/superglobals.php
/var/www/html/superglobals.php
<?php
$_GLOBALS['_MY_SUPER_GLOBAL'] = 'example';
/var/www/html/index.php
<?php
echo $_MY_SUPER_GLOBAL;