【问题标题】:Access static variable in non-static method + Inheritance在非静态方法+继承中访问静态变量
【发布时间】:2012-07-17 18:27:20
【问题描述】:

我有以下结构

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

【问题讨论】:

    标签: php oop inheritance static non-static


    【解决方案1】:

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

    【讨论】:

    • $a 在父类中公开时被声明为私有,这不是真正的错误吗?
    • @tigrang,我也想知道这一点,但如果他们没有收到任何错误,那么这只是建议/严格的更改,不应影响实际执行。
    • 我正在尝试使用 php 5.4 和 5.3.10 并因此出现致命错误。 codepad.viper-7.com/2THHHk
    【解决方案2】:

    查看我的代码

    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.
    

    【讨论】:

      猜你喜欢
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      • 2015-05-16
      • 2015-02-18
      • 2015-07-22
      • 2012-06-29
      • 1970-01-01
      • 2016-11-10
      相关资源
      最近更新 更多