将代码(方法)注入类? [英] injecting codes (methods) into class?
问题描述
以这个简单的代码为例:
Take this simple code:
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');
这个成本像 excpted 一样有效.我将该函数添加到 $customFunction
然后我可以从 run();
方法中调用它.
This cose works as excpted. I add that function to $customFunction
and then i can call it form run();
method.
问题出现在我注入的函数中,我尝试做一些与对象相关的事情,例如,如果我添加了这个函数:
The problem comes when in my injected function I try to do something object-related, for example if i add this function:
$c->customFunction['first'] = function(){ $this->callsomemethod(); }
当我调用 run();
方法时,PHP 说我不能在静态上下文中使用 $this
.
When i call the run();
method PHP says I can't use $this
in a static context.
我有什么方法可以注入这些函数并能够使用对象方法吗?
Do I have some way to inject those function and be able to use the object method?
(注意:当然我的课只是一个例子,我需要这个作为范围)
谢谢
(Note: of course my class is just an example, I need this for a scope)
Thanks
public function run($name) {
call_user_func($this->customFunction[$name],$this);
}
此时我只需要添加带有如下参数的函数:
At this point i just need to add function with a parm like this:
= function ($this) { /*some code*/};
并且 $this
将模拟对象上下文范围.
And $this
will emulate the object-context scope.
推荐答案
错误源于您在示例中显示为 /* some code*/
的代码.
The error originates in the code you have shown as /* some code*/
in your example.
您在此处分配匿名函数:
You assign an anonymous function here:
$c->customFunction['first'] = function (){ /* some code*/ };
它仍然只是一个函数.它不会成为类的真正方法.所以在里面使用 $this
是行不通的.
And it remains just a function. It doesn't become a real method of the class. So using $this
within it won't work.
解决方法:向您的自定义函数传递一个 $obj
参数,并让它们使用该参数而不是 $this
.(真的,只是一个古怪的解决方法;但可行.)
Workaround: Pass your custom functions an $obj
parameter, and have them use that instead of $this
. (Really, just a quirky workaround; but doable.)
call_user_func($this->customFunction[$name], $obj=$this);
或者尝试 classkit_method_add
或 runkit
以获得正确"的解决方案.- 如果在您的 PHP 中可用.
Or try classkit_method_add
or runkit
for a "proper" solution. - If available in your PHP.
这篇关于将代码(方法)注入类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!