【问题标题】:Why can't I use my instance in this trait?为什么我不能在这个特性中使用我的实例?
【发布时间】:2021-07-02 00:04:17
【问题描述】:

我有这个代码

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;
        }
    }
}

但是我收到错误$currentConfig must not be accessed before initialization。 var 转储向我展示了这一点:

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

为什么我不能在这里使用我的实例?

【问题讨论】:

    标签: php singleton instance traits


    【解决方案1】:

    问题不在于使用实例,而在于调用静态方法时未设置$currentConfig 属性。我认为解决此问题的最简单方法是为该属性赋予 null 默认值。

    private ?array $currentConfig = null;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-02
      • 1970-01-01
      • 2012-10-29
      • 1970-01-01
      • 2013-06-24
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      相关资源
      最近更新 更多