[ACCEPTED]-create superglobal variables in php?-php

Accepted answer
Score: 51

Static class variables can be referenced 1 globally, e.g.:

class myGlobals {

   static $myVariable;


function a() {

  print myGlobals::$myVariable;

Score: 36

Yes, it is possible, but not with the so-called 4 "core" PHP functionalities. You 3 have to install an extension called runkit7: Installation

After 2 that, you can set your custom superglobals 1 in php.ini as documented here: ini.runkit.superglobal

Score: 18

I think you already have it - every variable 2 you create in global space can be accessed 1 using the $GLOBALS superglobal like this:

// in global space
$myVar = "hello";

// inside a function
function foo() {
    echo $GLOBALS['myVar'];
Score: 7
   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()->someOtherClassName = new className;

class sampleClass {
    public function sampleMethod(){
        print_r(_REGISTRY()->sampleArray); echo '<br/>';
        echo _REGISTRY()->sampleVar.'<br/>';


$whatever = new sampleClass;



Score: 7

One other way to get around this issue is 6 to use a static class method or variable.

For 5 example:

class myGlobals {

   public static $myVariable;


Then, in your functions you can 4 simply refer to your global variable like 3 this:

function Test()
 echo myGlobals::$myVariable;

Not as clean as some other languages, but 2 at least you don't have to keep declaring 1 it global all the time.

Score: 6


There are only built-in superglobals listed 1 in this manual

Score: 5

Not really. though you can just abuse the 2 ones that are there if you don't mind the 1 ugliness of it.

Score: 2

You can also use the Environment variables 4 of the server, and access these in PHP This 3 is a good way to maybe store global database 2 access if you own and exclusively use the 1 server.

Score: 1

possible workaround with $GLOBALS:


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


echo $GLOBALS['xyz'];


Score: 1

One solution is to create your superglobal 5 variable in a separate php file and then 4 auto load that file with every php call 3 using the auto_prepend_file directive.

something like this 2 should work after restarting your php server 1 (your ini file location might be different):




  $_GLOBALS['_MY_SUPER_GLOBAL'] = 'example';



More Related questions