>  기사  >  백엔드 개발  >  PHP에서 새 개체에 메서드를 연결할 수 있나요?

PHP에서 새 개체에 메서드를 연결할 수 있나요?

Susan Sarandon
Susan Sarandon원래의
2024-10-18 14:59:03590검색

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.