PHP类被称为函数

mck*_*k89 2 php class function

有没有办法编写一个可以像函数一样调用的类?我的意思是这样的:

class test{}
$test = new test;
$test();
Run Code Online (Sandbox Code Playgroud)

我尝试使用__call魔术方法,但只有在访问其中存在的方法时才能使用它.也许可以使用SPL类或接口来完成?

Max*_*Max 5

使用__invoke魔术方法:

class test{
    public function __invoke()
    {
        return 'fooo';
    }
}

$test = new test;
print $test();
Run Code Online (Sandbox Code Playgroud)

但是你需要PHP 5.3.

根据您尝试做的另一种选择可能是使用闭包.