在父类中访问父属性会抛出错误-当不在对象上下文中使用$this时


Accessing parent property inside parent class throws error - using $this when not in object context

父类

class admarvel_generic_network
{
    protected $attributeSettings;
    public function __construct()
    {
        $this->attributeSettings = "something";
    }
    public static function parentGetAd()
    {
        print_r($this->attributeSettings); //throws FATAL ERROR Using $this when not in object context 
    }
}

子类-在静态函数中初始化同一类的对象

class Agencies_selectablemedia_test extends admarvel_generic_network
{
    public static function getAd($frengoAdParams)
    {
        $adnw = new Agencies_selectablemedia_test();
        $ad = $adnw->parentGetAd();
        return $ad;
    }
}   

//Entry point
$ad_contents = Agencies_selectablemedia_test::getAd($params);
echo $ad_contents;

我得到一个致命错误,如上面的代码中突出显示。

我检查了如果我在子类和父类中做以下更改-

父类

public static function parentGetAd($obj)
        {
            print_r($obj->attributeSettings); //this works
        }

子类

public static function getAd($frengoAdParams)
        {
            $adnw = new Agencies_selectablemedia_test();
            $ad = admarvel_generic_network::parentGetAd($adnw); //used scope resolution operator and passed object as parameter.
            return $ad;
        }

有人能解释一下吗?我想了解为什么我不能在父类的parentGetAd()函数中使用$this-> attributessettings。

不能访问$this->attributeSettings的原因是您处于静态方法中。所以你不在一个对象的上下文中。

public static function parentGetAd($obj)

如果你像这样声明方法

public function parentGetAd($obj) {
}

您应该能够访问$this->attributeSettings