PHP で新しいオブジェクトにメソッドを連鎖させることはできますか?

Susan Sarandon
リリース: 2024-10-18 14:59:03
オリジナル
590 人が閲覧しました

Can You Chain Methods on a New Object in PHP?

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()-&gt;xyz();</code>
ログイン後にコピー

In PHP 5.4+, the parser has been modified to allow chaining directly after instantiation:

<code class="php">(new Foo())-&gt;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()-&gt;xyz();</code>
ログイン後にコピー

以上がPHP で新しいオブジェクトにメソッドを連鎖させることはできますか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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