Create superglobals in php?

Is there a way to create my own superglobal variables like $ _POST and $ _GET?

+56
php
May 7 '09 at 12:55
source share
9 answers

Static class variables can be referenced globally, for example:

class myGlobals { static $myVariable; } function a() { print myGlobals::$myVariable; } 
+47
May 7 '09 at
source share

Yes, it’s possible, but not with the so-called β€œcore” PHP functionality. You must install an extension called runkit: http://www.php.net/manual/en/runkit.installation.php

After that, you can install your custom superglobal blocks in php.ini as described here: http://www.php.net/manual/en/runkit.configuration.php#ini.runkit.superglobal

+28
May 13, '14 at 17:35
source share

I think you already have this - every variable that you create in the global space can be accessed with $ GLOBALS suberglobal, like this:

 // in global space $myVar = "hello"; // inside a function function foo() { echo $GLOBALS['myVar']; } 
+18
May 7, '09 at 14:20
source share

Another way around this problem is to use a method or variable of a static class.

For example:

 class myGlobals { public static $myVariable; } 

Then in your functions, you can simply reference your global variable as follows:

 function Test() { echo myGlobals::$myVariable; } 

Not as clean as some other languages, but at least you don't need to constantly declare it global.

+6
Sep 23 '11 at 18:23
source share
  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(); 
+5
May 08 '11 at 13:58
source share

Not really. although you can simply abuse those that are, if you are not against ugliness.

+3
May 7 '09 at 12:59 a.m.
source share

No

There are only built-in superglobs listed in this guide.

+3
Sep 25 '13 at 18:12
source share

You can also use environment variables on the server and access them in PHP. This is a good way to store global access to the database if you own and use the server exclusively.

+1
May 7 '09 at 15:59
source share

possible workaround with $GLOBALS :

file.php:

 $GLOBALS['xyz'] = "hello"; 

any_included_file.php:

 echo $GLOBALS['xyz']; 
0
Dec 23 '17 at 10:14
source share



All Articles