PHP設計模式(6)- PHP鏈式操做

PHP鏈式操做:

形如:$db->where()->order()->limit()的語法模式,在一行代碼中完成多個方法的調用。鏈式操做的關鍵在於被調用的對象方法返回對象自己。

<?php class Database { private $sql; public function where($where) { $this->sql .= " where {$where}"; return $this; } public function order($order) { $this->sql .= " order by {$order}"; return $this; } public function limit($limit) { $this->sql .= " limit ({$limit})"; return $this; } public function go() { return $this->sql; } }$db = new Database();$stmt = $db->where('id=1 and name=2')->order('id DESC')->limit(10)->go(); ?>
相關文章
相關標籤/搜索