簡體   English   中英

通過非靜態方法+繼承訪問靜態變量

[英]Access static variable in non-static method + Inheritance

我有以下結構

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()都沒有成功。

update()更改self::$a

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

看我的代碼

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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM