2010-05-28 59 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