PHP 5.3
有没有办法做到这一点(例如在 java 中可行)
(new MyClass())->myMethod();
我收到:解析错误:语法错误,第 7 行 D.. 中意外的 T_OBJECT_OPERATOR
添加
我真的需要在下一个 PHP 版本中实现该 RFC!
http://wiki.php.net/rfc/instance-method-call
有没有一种方法可以让我们订阅它,从而获得更多关注?
最佳答案
不,这不可能。有一个 RFC
http://wiki.php.net/rfc/instance-method-call
但是没有人知道,这会在什么时候进入用户空间。
Jacob 提到了静态方法。还有其他或多或少有用的方法来实现相同的目的
function instanciate($className, $arg1 = null) {
$args = func_get_args();
array_shift($args);
$c = new ReflectionClass($className);
return $c->newInstanceArgs($c);
}
instanciate('Classname', 1, 2, 3)->doSomething();
但是,我更喜欢临时变量(就像问题中那样)。
更新: 我可以发誓过去问题中临时变量的例子。然而,我的意思是这个
$x = new Class;
$x->method();
其中 $x
是临时变量。
关于php - 在一行中实例化一个对象并调用一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5267242/