2010-05-28 16 views
8

Ho cercato di trovare una buona introduzione sugli oggetti OOP concatenabili in PHP, ma senza ancora un buon risultato.OOP PHP: oggetti concatenabili?

Come può essere fatto qualcosa del genere?

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

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

Thanks a lot!

risposta

17

La chiave è di restituire l'oggetto stesso all'interno di ciascun metodo:

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

Ogni metodo, che restituisce l'oggetto stesso, può essere utilizzato come intermedio in una catena metodo. Vedi Wikipedia’s article on Method chaining per ulteriori dettagli.

+0

Incredibile quanto sia facile questo è stato da fare. Non ne avevo idea. Grazie mille Gumbo! – Industrial

11

proprio ritorno $ questo nel add() e il tipo() metodi:

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

Un altro termine per questo è il Fluent Interface

+0

Aggiunta di una nota: il concatenamento dei metodi è una tecnica per la creazione di un'interfaccia fluente. – koen