mck89
mck89

Reputation: 19231

PHP class called as a function

is there a way to write a class that can be called 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?

Upvotes: 2

Views: 105

Answers (1)

BMBM
BMBM

Reputation: 16013

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.

Upvotes: 5

Related Questions