使一个全局变量可访问类中的每个函数 [英] Making a global variable accessible for every function inside a class
问题描述
我在全局范围上有一个名为 $ {SYSTEM}
的变量,其中SYSTEM是一个定义的常量。我有很多类的函数需要访问这个变量,我发现它讨厌的声明 global $ {SYSTEM};
每一次。 / p>
我试着声明一个类变量: public $ {SYSTEM} = $ GLOBALS [SYSTEM];
一个语法错误是奇怪的,因为我有另一个类,以这种方式声明类变量,似乎工作正常。我唯一能想到的是常数不被识别。
我已经设法使用一个构造函数,但我正在寻找一个更简单的
全局$ {SYSTEM} 变量是一个有很多其他子数组的数组。不幸的是,似乎没有办法使用构造函数...
<?php
//你想要的全局数组访问
$ GLOBALS ['uname'] = array('kernel-name'=>'Linux','kernel-release'=>'2.6.27-11-generic','machine' >'i686');
//用于引用全局变量的定义常量var
define(_SYSTEM_,'uname');
class Foo {
//你想要访问全局变量的方法var
public function bar(){
print_r($ this-> {_ SYSTEM_});
}
//这里的魔法发生在这里使用php5重载
public function __get($ d){
return $ GLOBALS [$ d];
}
}
$ foo = new Foo;
$ foo> bar();
?>
I have a variable on the global scope that is named ${SYSTEM}
, where SYSTEM is a defined constant. I've got a lot of classes with functions that need to have access to this variable and I'm finding it annoying declaring global ${SYSTEM};
every single time.
I tried declaring a class variable: public ${SYSTEM} = $GLOBALS[SYSTEM];
but this results in a syntax error which is weird because I have another class that declares class variables in this manner and seems to work fine. The only thing I can think of is that the constant isn't being recognised.
I have managed to pull this off with a constructor but I'm looking for a simpler solution before resorting to that.
EDIT The global ${SYSTEM} variable is an array with a lot of other child arrays in it. Unfortunately there doesn't seem to be a way to get around using a constructor...
Ok, hopefully I've got the gist of what you're trying to achieve
<?php
// the global array you want to access
$GLOBALS['uname'] = array('kernel-name' => 'Linux', 'kernel-release' => '2.6.27-11-generic', 'machine' => 'i686');
// the defined constant used to reference the global var
define(_SYSTEM_, 'uname');
class Foo {
// a method where you'd liked to access the global var
public function bar() {
print_r($this->{_SYSTEM_});
}
// the magic happens here using php5 overloading
public function __get($d) {
return $GLOBALS[$d];
}
}
$foo = new Foo;
$foo->bar();
?>
这篇关于使一个全局变量可访问类中的每个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!