给定一个具有成员函数f()的类a,下面显然是合理的代码:
( new A() )->f();
由于语法错误而失败:"意外的T_OBJECT_OPERATOR"。
对此有什么解释吗?
编辑:正如Mageek所猜测的,我正在努力理解这种行为;我已经知道如何解决它了。
这只适用于PHP 5.4。在此之前,您必须将实例分配给一个变量并使用该变量。
请参阅:http://www.php.net/manual/en/migration54.new-features.php
您要求的功能可以从PHP 5.4中获得。以下是PHP 5.4中的新功能列表:
http://docs.php.net/manual/en/migration54.new-features.php
已经添加了实例化时的类成员访问,例如(new Foo)->bar()。
但你可以试试这个技巧:
class TestClass {
protected $_testvar;
public function __construct($param) {
$this->_testvar = $param;
}
public function testMethod() {
return $this->_testvar;
}
}
function TestClass($param) { return new TestClass($param); }
现在你可以写:
$a = TestClass(2)->testMethod();