call_user_func(array($this, $method), $par) from parent's constructor?

匿名 (未验证) 提交于 2019-12-03 08:59:04

问题:

class Parent {    public function __construct($method) {     call_user_func(array($this, $method), 1);   }  }  class Child extends Parent {    public function __construct($method) {     parent::__construct($method);   }    protected function call_me_on_construct($par) {      echo $par;   }  } 

Creating instance of $child = new Child("call_me_on_construct"); I want call_me_on_construct method to be called. The problem is Parent's constructor know nothing about $this. What is better way to do it?

Thank you.

回答1:

It knows about $this. The only error in your code is that you use reserved keyword parent

class Ancestor {    public function __construct($method) {     call_user_func(array($this, $method), 1);   }  }  class Child extends Ancestor {    public function __construct($method) {     parent::__construct($method);   }    protected function call_me_on_construct($par) {      echo $par;   }  }  $c = new child("call_me_on_construct"); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!