PHP uses a variable from global space inside a class
Hi, I am writing PHP code. 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 the namespace or not and how? thanks Example:
<?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;
}
}
+3
source to share
1 answer
Try calling it $myvar
superglobal:
private static $container = $GLOBALS['myvar'];
Although, as Ron Dadon pointed out, this is generally bad practice in OOP.
EDIT:
I jumped here. My solution above doesn't really work, at least not for me. Thus, the best way to achieve this would be:
$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);
+3
source to share