0

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.

4

1 回答 1

4

您实际上只缺少一()对,这有效:

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

在 PHP 5.4 变更日志中它写道:

添加了对实例化的类成员访问,例如( new Foo ) ->bar()。

于 2013-07-02T19:31:33.800 回答