Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

__invoke() Method And Properties

<?php

class x {
    private X $y;
    
    function __invoke() { echo __METHOD__;}
    
    function foo() {
        $this->y = new X;
        $this->y();
        // better this way
        ($this->y)();
    }
}

(new X)->foo();

In the code here, the __invoke() makes the class X invokable : the object may be used as a function name and it will call the magic method __invoke.

Then, in the same class, there is a property $y, with the type of X. That property is, hence, holding an invokable object. So, may be, it is possible to call this property as a method, and invoke it?

Well, no. This call will yield an error, undefined method y. PHP doesn’t use the __invoke() here, as it would conflict with an existing y method. Also, that would make a case-sensitive method, as the property $Y doesn’t exists.

To invoke the object in the property y, one has to put parenthesis around the object, so that PHP can extract the object and then, invoke it safely.

See Also

PHP Features

Last updated: 10 September 2026