[英]PHP use variable from global space inside class
Hi I'm writing some code in PHP. 嗨,我正在用PHP编写一些代码。 I need to use a variable from the global scope inside my class but it doesn't work.
我需要在我的类中使用全局范围内的变量,但它不起作用。 I don't know if I need to use namespace or not and how ?
我不知道是否需要使用命名空间以及如何使用命名空间? Thank you Sample :
谢谢样品:
<?PHP
$plantask_global_script = array("one", "two");
$plantask_global_config = array("three", "four");
$myvar = array_merge($plantask_global_script, $plantask_global_config);
class Env implements ArrayAccess
{
static private $container = $myvar;
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
self::$container[] = $value;
} else {
self::$container[$offset] = $value;
}
}
public function offsetExists($offset)
{
return isset(self::$container[$offset]);
}
public function offsetUnset($offset)
{
unset(self::$container[$offset]);
}
public function offsetGet($offset)
{
return isset(self::$container[$offset]) ? self::$container[$offset] : null;
}
}
Try calling $myvar
as a superglobal: 尝试将
$myvar
称为超全局:
private static $container = $GLOBALS['myvar'];
Although, as Ron Dadon pointed out, this is generally bad practice in OOP. 虽然,正如Ron Dadon指出的那样,这在OOP中通常是不好的做法。
EDIT: 编辑:
I jumped the gun here. 我在这里跳了枪。 My above solution does not actually work , at least not for me.
我的上述解决方案实际上并不起作用 ,至少对我而言不是。 So, a better way to achieve this would be the following:
因此,实现这一目标的更好方法如下:
$myvar = array_merge($plantask_global_script, $plantask_global_config);
class Env implements ArrayAccess
{
private static $container = null;
public static function init($var)
{
self::$container = $var;
}
...
}
Env::init($myvar);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.