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

Barbara Streisand
Release: 2024-10-18 14:58:02
Original
169 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!