PHP OOP: Chainable objects?

非 Y 不嫁゛ 提交于 2019-12-03 12:54:04

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.

just return $this in the add() and type() methods:

function add() {
    // other code
    return $this;
}

Another term for this is the Fluent Interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!