Sco*_*nen 47
静态类变量可以全局引用,例如:
class myGlobals {
static $myVariable;
}
function a() {
print myGlobals::$myVariable;
}
Run Code Online (Sandbox Code Playgroud)
小智 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
One*_*erd 18
我想你已经拥有它 - 你在全球空间创建的每个变量都可以使用$ GLOBALS suberglobal 访问:
// in global space
$myVar = "hello";
// inside a function
function foo() {
echo $GLOBALS['myVar'];
}
Run Code Online (Sandbox Code Playgroud)
小智 6
解决此问题的另一种方法是使用静态类方法或变量.
例如:
class myGlobals {
public static $myVariable;
}
Run Code Online (Sandbox Code Playgroud)
然后,在您的函数中,您可以简单地引用您的全局变量,如下所示:
function Test()
{
echo myGlobals::$myVariable;
}
Run Code Online (Sandbox Code Playgroud)
不像其他语言一样干净,但至少你不必一直声明它是全局的.
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)