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>
Das obige ist der detaillierte Inhalt vonKönnen Sie Methoden für ein neues Objekt in PHP verketten?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!