首頁 > 後端開發 > php教程 > 可以在 PHP 中連結新物件上的方法嗎?

可以在 PHP 中連結新物件上的方法嗎?

Susan Sarandon
發布: 2024-10-18 14:59:03
原創
727 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板