Search code examples
phpoopmagic-function

Immediate 1-line magic method call on new PHP object


I'd like to immediately call a magic method (__call()) on a newly constructed object. Example:

class Foo {
    public function __call($method,$args) {
        echo "You were looking for the method $method.\n";
    }
}

Ideal (but gets a parse error):

$foo = new Foo()->bar(); // Fails :(

Working:

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

Is this possible? I know PHP 5.4 brought immediate 1-line object method calling (http://docs.php.net/manual/en/migration54.new-features.php) so I'm not sure why this isn't working.


Solution

  • You are actually only missing a () pair, this works:

    $foo = (new Foo())->bar(); // this works.
    

    In the PHP 5.4 changelog it writes:

    Class member access on instantiation has been added, e.g. ( new Foo )->bar().