2010-05-28 58 views
8

我试图找到一个很好的介绍PHP中的可链式OOP对象,但没有任何好的结果呢。PHP OOP:可链接对象?

怎么能这样做呢?

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

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

非常感谢!

回答

17

的关键是每个方法内返回对象本身:

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

每一个方法,它返回对象本身,可以使用如在方法链的中间。有关更多详细信息,请参见Wikipedia’s article on Method chaining

+0

惊人多么容易,这是做的。不知道。非常感谢Gumbo! – Industrial 2010-05-28 15:25:51

11

只返回$这在add()和类型()方法:

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

另一个术语,这是Fluent Interface

+0

添加注释:方法链只是创建流畅接口的一种技巧。 – koen 2010-05-28 19:29:45