在非静态方法中访问静态变量+继承

时间:2012-07-18 16:33:08

标签: php oop inheritance static non-static

我有以下结构

class Foo
{
    public static $a = "parent";

    public static function Load()
    {
        return static::$a;
    }

    public function Update()
    {
        return self::$a; 
    }

}

class Bar extends Foo
{
    private static $a = "child";
}

我希望Update功能能够返回$ a,但我无法让它工作。

Bar::Load();  //returns child, Correct.
$bar = new Bar();
$bar->Update(); //returns parent, Wrong.

我尝试过self ::,static ::和get_class()但没有成功。

2 个答案:

答案 0 :(得分:3)

更改self::$a

中的update()
class Foo
{
    protected static $a = "parent"; // Notice this is now "protected"

    public function child()
    {
        return static::$a; 
    }

    public function parent()
    {
        return self::$a; 
    }
}

class Bar extends Foo
{
    protected static $a = "child"; // Notice this is now "protected"
}

$bar = new Bar();
print $bar->child() . "\n";
print $bar->parent() . "\n";

答案 1 :(得分:1)

查看我的代码

class Foo
{
    protected static $a = "parent";

    public static function Load()
    {
        return static::$a;
    }

    public function Update()
    {
        return static::$a; 
    }

}

class Bar extends Foo
{
    protected static $a = "child";
}
Bar::Load();  //returns child, Correct.
$bar = new Bar();
$bar->Update(); //returns child, Correct.