PHP class called as a function
is there a way to write a class that can be c开发者_运维百科alled like a function? I mean something like this:
class test{}
$test = new test;
$test();
I tried with the __call
magic method but it can be used only when accessing in-existent methods on it. Maybe it can be done using SPL classes or interfaces?
Use the __invoke magic method:
class test{
public function __invoke()
{
return 'fooo';
}
}
$test = new test;
print $test();
But you need PHP 5.3 for this.
Another alternative depending on what you are trying to do might be using a closure.
精彩评论