使用$ this访问子级中的父级属性

Roh*_*pra 5 php oop

我正在尝试创建一个简单的MVC,我个人使用,我真的可以使用这个简单问题的答案

class theParent extends grandParent{

    protected $hello = "Hello World";

    public function __construct() {
        parent::__construct();
    }

    public function route_to($where) {
        call_user_func(array("Child", $where), $this);
    }
}

class Child extends theParent {

    public function  __construct() {
        parent::__construct();
    }

    public function index($var) {
        echo $this->hello;
    }

}

$x = new theParent();
$x->route_to('index');
Run Code Online (Sandbox Code Playgroud)

现在Child::index()这会引发一个致命的错误:Using $this when not in object context但如果我使用echo $var->hello,它就可以了.

我知道我可以$var用来访问父母的所有属性,但我宁愿使用$this.

Nik*_*kiC 6

通过编写,call_user_func(array("Child", $where), $this)您静态调用该方法.但由于您的方法不是静态的,您需要某种对象实例:

call_user_func(array(new Child, $where), $this);
Run Code Online (Sandbox Code Playgroud)

关于回调函数的文档.


Chr*_*ker 4

当您执行以下操作时,您没有实例来Child调用非静态方法$x->route_to('index'); 您调用该方法的方式(无需先创建实例)隐含静态。

有两种方法可以纠正它。要么使Child类的方法静态:

class Child extends theParent {

    public function  __construct() {
        parent::__construct();
    }

    static public function index($var) {
        echo self::$hello;
    }

}
Run Code Online (Sandbox Code Playgroud)

...或者创建子类的实例供父类使用:

   class theParent extends grandParent{

        protected $hello = "Hello World";
        private $child = false

        public function __construct() {
            parent::__construct();
        }

        public function route_to($where) {
            if ($this->child == false)
              $this->child = new Child();
            call_user_func(array($this->child, $where), $this);
        }
    }
Run Code Online (Sandbox Code Playgroud)

当然,这两个示例都相当通用且无用,但您已经看到了这个概念。