php链式操作的实现方式

2019-09-27 23:29 · php · YUSHUI

类似$db->where("id=36")->limit("10")->order("uid desc"),链式操作的实现方式


先讲下方法的常规调用;

namespace Com;

class Database{

    function where($where){
        echo $where;
    }

    function order($order){
        echo $order;
    }

    function limit($limit){
        echo $limit;
    }
}

调用
$db = new  \Com\Database();
$db->where();
$db->limit();
缺点:实现多个方法需要多行调用;

链式操作,在方法返回return $this;即可使用链式操作;
namespace Com;

class Database{

    function where($where){
        echo $where;


        return $this;
    }

    function order($order){
        echo $order;


        return $this;
    }

    function limit($limit){
        echo $limit;


        return $this;
    }
}

使用链式调用:
$db->where("id=36")->limit("10")->order("uid desc")  ;

← 返回首页

文章评论

登录后评论

1312 · 2020-05-27 02:40

来了