将代码(方法)注入类中?

3 php oop

拿这个简单的代码:

class MyClass {
   public $customFunction = array();

   public function run($name){
       call_user_func($this->customFunction[$name]);
   }
}

//> Usage:

$c = new MyClass();
$c->customFunction['first'] = function (){ /* some code*/ };

$c->run('first');
Run Code Online (Sandbox Code Playgroud)

这个cose作为被激发的.我添加该功能$customFunction,然后我可以称之为表单run();方法.

问题出现在我注入的函数中,我尝试做一些与对象相关的事情,例如,如果我添加这个函数:

$c->customFunction['first'] = function(){ $this->callsomemethod(); }
Run Code Online (Sandbox Code Playgroud)

当我调用run();PHP 的方法时,我说我不能$this在静态上下文中使用.

我有办法注入这些功能并能够使用对象方法吗?

(注意:当然我的课只是一个例子,我需要这个范围)
谢谢

感谢Mario,我将使用以下解决方案:

public function run($name) {
    call_user_func($this->customFunction[$name],$this);
}
Run Code Online (Sandbox Code Playgroud)

在这一点上,我只需要像这样添加parm函数:

= function ($this) { /*some code*/};
Run Code Online (Sandbox Code Playgroud)

$this将模拟对象上下文范围.

mar*_*rio 5

该错误源自您/* some code*/在示例中显示的代码.

您在此处指定匿名函数:

$c->customFunction['first'] = function (){ /* some code*/ };
Run Code Online (Sandbox Code Playgroud)

它仍然只是一个功能.它不会成为班级的真正方法.所以$this在它内部使用是行不通的.


解决方法:将自定义函数传递给$obj参数,并让它们使用它而不是$this.(真的,只是一个古怪的解决方法;但可行.)

call_user_func($this->customFunction[$name], $obj=$this);
Run Code Online (Sandbox Code Playgroud)

或尝试classkit_method_addrunkit"适当"的解决方案. - 如果你的PHP可用.