首页 > 编程 > PHP > 正文

【PHP】链式操作的实现

2019-11-08 02:32:51
字体:
来源:转载
供稿:网友

在使用框架的过程中,我们经常遇到过以下这种语句

$database->where("id = 1")->order("id desc")->limit(10);

这种操作被称为链式操作。

实现上述操作只需要掌握一种技巧,比如:

Database.php

<?phpclass Database{ function where($where) { } function order($order) { } function limit($limit) { }}

test.php

include "Database.php"$database = new Database();$database->where("id > 10");$database->order("id desc");$database->limit(10);

如要实现链式操作,只需要修改Database.php

class Database{ function where($where) { return $this;//重点 } function order($order) { return $this; } function limit($limit) { return $this; }}

test.php

$database->where("id = 1")->order("id desc")->limit(10);
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表