php 在实例中设置匿名函数 [英] php Set a anonymous function in an instance
问题描述
我刚刚开始使用 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.
例如,让我们说...
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).
非常感谢您抽出宝贵时间!
Thanks so very much for your time!!
-GK
推荐答案
您可以使用 __call 这个工作的魔法函数.不漂亮,但很管用..
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屋!