开发者

PHP class called as a function

开发者 https://www.devze.com 2023-04-03 08:49 出处:网络
is there a way to write a class that can be c开发者_运维百科alled like a function? I mean something like this:

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

精彩评论

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