PHP で新しく作成されたオブジェクトにメソッド チェーンを実装するにはどうすればよいですか?

Barbara Streisand
リリース: 2024-10-18 14:58:02
オリジナル
168 人が閲覧しました

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.

以上がPHP で新しく作成されたオブジェクトにメソッド チェーンを実装するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!