首页 > 后端开发 > php教程 > 可以在 PHP 中链接新对象上的方法吗?

可以在 PHP 中链接新对象上的方法吗?

Susan Sarandon
发布: 2024-10-18 14:59:03
原创
734 人浏览过

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
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板