有没有办法编写一个可以像函数一样调用的类?我的意思是这样的:
class test{}
$test = new test;
$test();
我尝试使用 __call
魔术方法,但它只能在访问其上不存在的方法时使用。也许可以使用 SPL 类或接口(interface)来完成?
最佳答案
class test{
public function __invoke()
{
return 'fooo';
}
}
$test = new test;
print $test();
但是您需要 PHP 5.3。
根据您想要执行的操作,另一种选择可能是使用 closure .
关于作为函数调用的 PHP 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7330392/