php在实例中设置匿名函数 [英] php Set a anonymous function in an instance
本文介绍了php在实例中设置匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚刚开始使用PHP,我想知道是否有一种方法可以添加一个匿名函数到类实例。
I am just starting out with PHP, and I am wondering if there is a way to add an anonymous function to a class instance.
例如,让我们说...
For instance, lets say...
class A{
public B;
}
$c = new A();
//This is where I am getting a little confused...
//The following wont work
$c->B = function(){echo('HelloWorld');};
$c->B();
我希望做的是在大量不同的应用程序中重用相同的代码,
What I am hoping to do is reuse the same spit of code in a great number of different applications, and make it so that I can just 'swap-out' and replace functions in specific instances.
我使用的是php5.3(所以匿名函数应该工作,只是没有
I am using php5.3 (so anonymous functions should work, just not in the way that I am using them).
非常感谢您的时间!
GK
推荐答案
您可以使用 __调用此作业的魔术函数。不是美容,但它工作..
You can use the __call magic function for this job. Not a beauty, but it works..
像这样:
class A {
public $B;
public function __call($closure, $args)
{
call_user_func_array($this->$closure, $args);
}
}
$c = new A();
$c->B = function () { echo('HelloWorld'); };
$c->B();
这篇关于php在实例中设置匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文