willy willy - 3 months ago 8
PHP Question

Define a Class Function Operator

How can I define in PHP a class

Foo
that allows to do something like:

$foo = new Foo();
$foo->bar;
$foo();

Answer

You're asking about invokable objects, or treating objects as functions. To be able to do that, you need to implement __invoke() method, like this:

class Foo {
    public function __invoke()
    {
        echo 'invoke!';
    }
}

Read more: http://php.net/manual/en/language.oop5.magic.php#object.invoke

Also, you can call $foo->bar; as many times as you want, just as you can write: $a = 5; $a; - but it will have no effect. It's just a field. If it's a callable, you'll have to add parentheses to call it.

Comments