Home >Backend Development >PHP Tutorial >How to Implement Method Chaining on Newly Created Objects in PHP?

How to Implement Method Chaining on Newly Created Objects in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-18 14:58:02271browse

How to Implement Method Chaining on Newly Created Objects in PHP?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn