call_user_func(array($this, $method), $par) from p

2019-05-27 11:07发布

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.

标签: php oop
1条回答
乱世女痞
2楼-- · 2019-05-27 11:43

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");
查看更多
登录 后发表回答