aef*_*fxx 55 php constructor new-operator method-chaining
我想知道是否有办法在PHP中新创建的对象上链接方法?
就像是:
class Foo {
public function xyz() { ... return $this; }
}
$my_foo = new Foo()->xyz();
Run Code Online (Sandbox Code Playgroud)
有人知道实现这个目标的方法吗?
Ala*_*orm 99
在PHP 5.4+中,解析器已被修改,因此您可以执行此类操作
(new Foo())->xyz();
Run Code Online (Sandbox Code Playgroud)
将实例化包装在括号中,然后链接掉.
在PHP 5.4之前,当你使用的时候
new Classname();
Run Code Online (Sandbox Code Playgroud)
语法,你不能链接实例化的方法调用.这是PHP 5.3语法的限制.实例化对象后,您可以链接掉.
我以前看到过的一种解决方法是某种静态实例化方法.
class Foo
{
public function xyz()
{
echo "Called","\n";
return $this;
}
static public function instantiate()
{
return new self();
}
}
$a = Foo::instantiate()->xyz();
Run Code Online (Sandbox Code Playgroud)
通过在静态方法中将调用包装到new,您可以使用方法调用实例化一个类,然后您可以自由地链接它.
Ken*_*iah 23
定义这样的全局函数:
function with($object){ return $object; }
Run Code Online (Sandbox Code Playgroud)
然后您就可以致电:
with(new Foo)->xyz();
Run Code Online (Sandbox Code Playgroud)
Jac*_*son 11
在PHP 5.4中,您可以链接一个新实例化的对象:
http://docs.php.net/manual/en/migration54.new-features.php
对于旧版本的PHP,您可以使用Alan Storm的解决方案.
这个答案已经过时了 - 因此想要纠正它.
在PHP 5.4.x中,您可以将方法链接到新调用.我们以这个类为例:
<?php class a {
public function __construct() { echo "Constructed\n"; }
public function foo() { echo "Foobar'd!\n"; }
}
Run Code Online (Sandbox Code Playgroud)
现在,我们可以使用这个: $b = (new a())->foo();
输出是:
Constructed
Foobar'd!
Run Code Online (Sandbox Code Playgroud)
更多信息可在手册中找到:http://www.php.net/manual/en/migration54.new-features.php