ato*_*rri 13 php variables global class function
我有一个名为全局范围的变量${SYSTEM},其中SYSTEM是一个已定义的常量.我有很多类需要访问这个变量的函数,我发现global ${SYSTEM};每次都声明这很烦人.
我尝试声明一个类变量:public ${SYSTEM} = $GLOBALS[SYSTEM];但是这会导致语法错误很奇怪,因为我有另一个以这种方式声明类变量的类,似乎工作正常.我唯一能想到的是这个常数没有得到认可.
我已经设法用一个构造函数来解决这个问题,但我正在寻找一个更简单的解决方案.
编辑 全局$ {SYSTEM}变量是一个包含许多其他子数组的数组.不幸的是,似乎没有办法绕过使用构造函数...
好的,希望我已经掌握了你想要实现的目标
<?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();
?>
Run Code Online (Sandbox Code Playgroud)
这就是我在全球范围内访问全球的方式.
class exampleGetInstance
{
private static $instance;
public $value1;
public $value2;
private function initialize()
{
$this->value1 = 'test value';
$this->value2 = 'test value2';
}
public function getInstance()
{
if (!isset(self::$instance))
{
$class = __CLASS__;
self::$instance = new $class();
self::$instance->initialize();
}
return self::$instance;
}
}
$myInstance = exampleGetInstance::getInstance();
echo $myInstance->value1;
Run Code Online (Sandbox Code Playgroud)
$myInstance现在是对exampleGetInstance类实例的引用.
固定格式