简体   繁体   English

如何用非静态方法覆盖静态方法?

[英]How to override static methods with non static methods?

How to override static methods with non static methods? 如何用非静态方法覆盖静态方法?

code

class Env {
    static protected $vars = [
    ];

    static public function get_env_var($var){
        return self::$vars[$var];
    }

    static public function set_env_var($var, $value){
        self::$vars[$var] = $value;
    }
}

class Test extends Env {
    private $env_vars = [];

    public function __construct(){
        $this->env_vars = self::$vars;
    }

    public function get_env_var($var){
        return $this->env_vars[$var];
    }

    public function set_env_var($var, $value){
        $this->env_vars[$var] = $value;
    }
}

$Test = new Test();

error 错误

Cannot make static method Env::get_env_var() non static in class Test in

You can't. 你不能

If you defined them as static before, you had valid reasons. 如果以前将它们定义为static ,则有充分的理由。

Original question was how to override static method to non static. 最初的问题是如何将静态方法重写为非静态方法。 Your answer is not the answer for the question, because child is still static. 您的答案不是问题的答案,因为孩子仍然是静态的。

You can't override a static method with a non static. 您不能使用非静态方法覆盖静态方法。

public static function get_env_var($var)
class Parent
{
    public static function start()
    {
        echo 'Parent::start';
    }
}

class Child extends Parent
{
    public static function start()
    {
        parent::start();
        echo 'Child::start';
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM