开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜