什么是链式操作
我们经常会在一些应用框架中看到如下代码:
$db = new Database;
$db->where('cid = 9')->order('aid desc')->limit(10);
看起来很酷很炫,此即为PHP的链式操作。
代码实现
复制代码
class Database {
public function where($where) {
return $this;
}
public function order($order) {
return $this;
}
public function limit($limit) {
return $this;
}
}
复制代码
其关键内容就是在方法中返回return $this,使得方法的返回值再次指向类对象本身,可再进行二次调用。
传统调用方法
$db->where('cid = 9');
$db->order('aid desc');
$db->limit(10);
相比传统调用方法,采用链式操作后,一步到位,牛叉的狠。
时代在变迁,技术不断进度,代码既要好用,还得优雅。
目前链式操作的应用在数据库操作上使用的较多,其他方面可自行挖掘。