您好我正在寫一些代碼在PHP中。我需要在全班範圍內使用全局範圍的變量,但它不起作用。我不知道我是否需要使用命名空間,以及如何使用命名空間?謝謝 樣品:PHP使用變量從全球空間裏面類
<?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;
}
}
嘗試在您的類的第一行添加代碼:global $ myvar; –
順便說一下,全局變量通常不是很好的OOP練習,它們會創建類與全局變量的緊密耦合 –
爲了避免$ GLOBALS,您可以創建一個getter和一個setter方法來在類中使用該值。 –