如何在新创建的对象上链式方法? [英] How to chain method on a newly created object?
问题描述
我想知道在PHP中新建对象是否有链接方法?
类似:
class Foo {
public function xyz(){... return $ this; }
}
$ my_foo = new Foo() - > xyz();任何人都知道实现这一点的方法吗?
解决方案
在PHP 5.4+中,解析器已被修改,所以你可以这样做
(new Foo()) - > xyz();
将实例化括在括号中,并链接起来。
在PHP 5.4之前,当您使用
new Classname();
语法,您无法将方法调用链接到实例化。这是PHP 5.3的语法的限制。一旦对象被实例化,你可以链接起来。
我曾经看过的一种方法是一种静态实例化方法。
class Foo
{
public function xyz()
{
echo Called,\\\
;
return $ this;
}
static public function instantiate()
{
return new self();
}
}
$ a = Foo :: instantiate() - > xyz();
通过在静态方法中调用new,您可以使用方法调用实例化一个类,你可以自由链接。
I would like to know whether there's a way to chain methods on a newly created object in PHP?
Something like:
class Foo {
public function xyz() { ... return $this; }
}
$my_foo = new Foo()->xyz();
Anyone know of a way to achieve this?
In PHP 5.4+, the parser's been modified so you can do something like this
(new Foo())->xyz();
Wrap the instantiation in parenthesis, and chain away.
Prior to PHP 5.4, when you're using the
new Classname();
syntax, you can't chain a method call off the instantiation. It's a limitation of PHP 5.3's syntax. Once an object is instantiated, you can chain away.
One method I've seen used to get around this is a static instantiation method of some kind.
class Foo
{
public function xyz()
{
echo "Called","\n";
return $this;
}
static public function instantiate()
{
return new self();
}
}
$a = Foo::instantiate()->xyz();
By wrapping the call to new in a static method, you can instantiate a class with method call, and you're then free to chain off that.
这篇关于如何在新创建的对象上链式方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!