在php中创建超全局变量?

Moo*_*oon 57 php

有没有办法创建我自己的自定义超全局变量,如$ _POST和$ _GET?

Sco*_*nen 47

静态类变量可以全局引用,例如:

class myGlobals {

   static $myVariable;

}

function a() {

  print myGlobals::$myVariable;

}
Run Code Online (Sandbox Code Playgroud)

  • 你先生,让我开心。但它只在课堂内有效吗?有没有办法在课外做到这一点? (2认同)

小智 29

是的,这是可能的,但不是所谓的"核心"PHP功能.您必须安装名为runkit的扩展程序:http://www.php.net/manual/en/runkit.installation.php

之后,您可以在php.ini中设置自定义超级全局,如下所示:http: //www.php.net/manual/en/runkit.configuration.php#ini.runkit.superglobal

  • 这是实际回答这个问题的唯一答案.其他的基本上都是"不,但你可以这样做".+1,我希望它更高. (7认同)

One*_*erd 18

我想你已经拥有它 - 你在全球空间创建的每个变量都可以使用$ GLOBALS suberglobal 访问:

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

// inside a function
function foo() {
    echo $GLOBALS['myVar'];
}
Run Code Online (Sandbox Code Playgroud)

  • 与仅使用变量本身相比,使用$ GLOBALS数组的性能如何? (2认同)

小智 6

解决此问题的另一种方法是使用静态类方法或变量.

例如:

class myGlobals {

   public static $myVariable;

}
Run Code Online (Sandbox Code Playgroud)

然后,在您的函数中,您可以简单地引用您的全局变量,如下所示:

function Test()
{
 echo myGlobals::$myVariable;
}
Run Code Online (Sandbox Code Playgroud)

不像其他语言一样干净,但至少你不必一直声明它是全局的.


Geo*_*Geo 6

本手册中仅列出了内置超全局变量


Rik*_*ood 5

并不真地。不过,如果你不介意它的丑陋,你可以滥用那里的那些。


Gun*_*rss 5

   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();
Run Code Online (Sandbox Code Playgroud)

  • 在此答案中添加说明将有助于人们了解您所做的工作. (5认同)