问题
I have tried to find a good introduction on chainable OOP objects in PHP, but without any good result yet.
How can something like this be done?
$this->className->add('1','value');
$this->className->type('string');
$this->classname->doStuff();
Or even: $this->className->add('1','value')->type('string')->doStuff();
Thanks a lot!
回答1:
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.
回答2:
just return $this in the add() and type() methods:
function add() {
// other code
return $this;
}
回答3:
Another term for this is the Fluent Interface
来源:https://stackoverflow.com/questions/2929928/php-oop-chainable-objects