访问父类中的父属性会引发错误 - 在不在对象上下文中时使用$ this

时间:2015-09-01 10:46:16

标签: php oop

父类

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-> attributeSettings。

1 个答案:

答案 0 :(得分:1)

您无法访问$this->attributeSettings的原因是您使用的是静态方法。所以你不是在一个物体的背景下。

public static function parentGetAd($obj)

如果您要声明这样的方法

public function parentGetAd($obj) {

}

您应该可以访问$this->attributeSettings

相关问题