In Codeigniter, we can do :
$this->select('users')->orderBy('id')->limit(20)
I think this way of attaching 开发者_运维技巧methods to each other can work very good for me in my simple set of classes, but how to do it ?
This is called a fluent interface. To implement it, the function simply needs to return itself. Since the object is returned by reference, you can then chain together multiple calls:
class SomeClass
{
public function select($table)
{
// do stuff
return $this;
}
public function orderBy($order)
{
// do stuff
return $this;
}
}
I believe you can do this by returning the object at the end of the function. For example:
class GreetClass {
function __construct($greeting) {
$this->greeting = $greeting;
}
function a() {
echo $this->greeting;
return $this;
}
function b() {
echo ' ';
return $this;
}
function c($who) {
echo $who;
}
}
$obj = new GreetClass('Hello');
$obj->a()->b()->c('World'); // Echoes: Hello World
精彩评论