可以在 php 运行时将函数分配给类变量吗?
是否可以在运行时将要执行的函数分配给类变量?一种像 C
这样的“函数指针”:(这不起作用,因为 sum 超出了 A 的范围,但这就是我的意思)
class A {
public $function_name;
public functon run($arg1,$arg2){
$function_name($arg1,$arg2);
}
}
function sum($a,$b){
echo $a+$b;
}
$a=new A();
$a->function_name='sum';
$a->run();
[编辑] 我知道有“call_user_func”,但据我了解,它需要在范围内包含该函数或使用公共类方法
it is possible to assign to a class variable a function at runtime to be executed? a kind of "function pointer" like C
something like this: (this won't work because sum is out of the scope of A, but this is the pattern i mean)
class A {
public $function_name;
public functon run($arg1,$arg2){
$function_name($arg1,$arg2);
}
}
function sum($a,$b){
echo $a+$b;
}
$a=new A();
$a->function_name='sum';
$a->run();
[edit]
i know there is "call_user_func" but it need as i understand to have the function in the scope or use a public class method
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您使用 PHP > 5.3.0,则可以使用 匿名函数:
You could use an anonymous function if you use PHP >5.3.0:
使用 call_user_func_array:
Using call_user_func_array:
无论范围如何,它都有效。您只需使用
call_user_func
。我还修复了您的示例中的一些拼写错误。实例
It works regardless of scope. You just gotta call it using
call_user_func
. I also fixed a couple of typos in your example.Live example
另一种方式是使用可变变量(适用于对象方法)
Another way is to make use variable variables (applicable to object method)
使用 Callback 伪类型的任何变体。
与 call_user_func 或 call_user_func_array
该手册给出了上述内容的很好的使用示例。
如果您想,另请参阅新的 php 5.4 Closure::bindTO 方法能够轻松地使用其中的 $this 关键字。
Use any variation of the Callback pseudo type.
Use it with call_user_func or call_user_func_array
The manual gives great examples of usage for the above.
Also see the new php 5.4 Closure::bindTO method if you want to be able to easily use the $this keyword in it.