如何在PHP5中构建多oop函数

Par*_*ser 2 php oop method-chaining

我在PHP5中有一个关于OOP的问题.我看到越来越多的代码编写如下:

$object->function()->first(array('str','str','str'))->second(array(1,2,3,4,5));
Run Code Online (Sandbox Code Playgroud)

但我不知道如何创建这种方法.我希望有人能在这里帮助我,:0)非常感谢.

cHa*_*Hao 8

在您自己的类中链接类似方法的关键是返回一个对象(几乎总是$this),然后将其用作下一个方法调用的对象.

像这样:

class example
{
    public function a_function()
    {
         return $this;
    }

    public function first($some_array)
    {
         // do some stuff with $some_array, then...
         return $this;
    }
    public function second($some_other_array)
    {
         // do some stuff
         return $this;
    }
}

$obj = new example();
$obj->a_function()->first(array('str', 'str', 'str'))->second(array(1, 2, 3, 4, 5));
Run Code Online (Sandbox Code Playgroud)

注意,可以返回除了之外的对象$this,并且上面的链接实际上只是一个较短的说法$a = $obj->first(...); $b = $a->second(...);,减去设置变量的丑陋,你将永远不会再次使用它.

  • 仅供参考:此技术用于创建Fluent界面(http://en.wikipedia.org/wiki/Fluent_interface). (4认同)