Question

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.

Was it helpful?

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().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top