Search code examples
phpsingletoninstancetraits

Why can't I use my instance in this trait?


I have this code

trait GetCurrentConfigTrait
{

    private static ?object $instance;
    private ?array $currentConfig;

    final public static function getCurrentConfig($name)
    {
        $class = __CLASS__;
        self::$instance = self::$instance ?? new $class();

        var_dump(self::$instance);

        if(is_array(self::$instance->currentConfig)){ # <<< This line throws the error.
            return self::$instance->currentConfig;
        }
        else{
            //Load config
            return self::$instance->currentConfig;
        }
    }
}

However I get the error $currentConfig must not be accessed before initialization. The var dump shows me this:

object(My\Class)#1 (0) { ["currentConfig":"My\Class":private]=> uninitialized(?array) }

Why can't I use my instance here?


Solution

  • The problem isn't with using the instance, it's just that the $currentConfig property isn't set when you call the static method. I think the simplest way to fix the problem would be to give that property a null default value.

    private ?array $currentConfig = null;