Method Chaining in PHP for New Objects
In PHP, method chaining allows you to execute multiple methods on an object in a single statement. However, it's not immediately clear how to achieve this when creating a new object.
Chaining on Newly Created Objects
From PHP 5.4 onwards, a simple and elegant solution exists:
<code class="php">(new Foo())->xyz();</code>
Enclosing the new instance in parentheses enables you to chain methods directly after instantiation.
Prior to PHP 5.4
Before PHP 5.4, chaining was not possible with the following syntax:
<code class="php">new Classname();</code>
As a workaround, a static instantiation method can be employed:
<code class="php">class Foo { public static function instantiate() { return new self(); } } $a = Foo::instantiate()->xyz();</code>
This allows chaining by wrapping the new instance in a static method.
The above is the detailed content of How to Implement Method Chaining on Newly Created Objects in PHP?. For more information, please follow other related articles on the PHP Chinese website!