Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP use variable from global space inside class

Tags:

scope

php

class

Hi I'm writing some code in 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;
    }
}
like image 510
Antoine Pointeau Avatar asked Nov 19 '25 06:11

Antoine Pointeau


1 Answers

Try calling $myvar as a superglobal:

private static $container = $GLOBALS['myvar'];

Although, as Ron Dadon pointed out, this is generally bad practice in 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);
like image 127
Stuart Wagner Avatar answered Nov 21 '25 20:11

Stuart Wagner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!