可以在 PHP 中链接新对象上的方法吗?
Chaining Methods on a Newly Created Object
In PHP, it's not immediately clear if it's possible to chain methods on a newly created object. This question explores this question, asking if there's a way to achieve the following syntax:
<code class="php">class Foo { public function xyz() { ... return $this; } } $my_foo = new Foo()->xyz();</code>
In PHP 5.4+, the parser has been modified to allow chaining directly after instantiation:
<code class="php">(new Foo())->xyz();</code>
Simply wrap the instantiation in parentheses and proceed with chaining.
However, in PHP 5.3 and earlier, chaining directly after instantiation is not possible due to limitations in the syntax. To workaround this, one can use a static instantiation method:
<code class="php">class Foo { public function xyz() { echo "Called","\n"; return $this; } static public function instantiate() { return new self(); } } $a = Foo::instantiate()->xyz();</code>
以上是可以在 PHP 中链接新对象上的方法吗?的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)