PHP OOP:可链接对象? [英] PHP OOP: Chainable objects?

查看:75
本文介绍了PHP OOP:可链接对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到有关PHP中可链接的OOP对象的很好的介绍,但没有任何好的结果.

I have tried to find a good introduction on chainable OOP objects in PHP, but without any good result yet.

怎么做这样的事情?

$this->className->add('1','value');
$this->className->type('string');
$this->classname->doStuff();

甚至:$this->className->add('1','value')->type('string')->doStuff();

非常感谢!

推荐答案

关键是要在每种方法中返回对象本身:

The key is to return the object itself within each method:

class Foo {
    function add($arg1, $arg2) {
        // …
        return $this;
    }
    function type($arg1) {
        // …
        return $this;
    }
    function doStuff() {
        // …
        return $this;
    }
}

返回对象本身的每个方法都可以用作方法链中的中间方法.有关更多详细信息,请参见维基百科有关方法链接 的文章.

Every method, that returns the object itself, can be used as an intermediate in a method chain. See Wikipedia’s article on Method chaining for some further details.

这篇关于PHP OOP:可链接对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆