zoukankan      html  css  js  c++  java
  • PHP实现链式操作

    什么是链式操作

    我们经常会在一些应用框架中看到如下代码:

    $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);

    相比传统调用方法,采用链式操作后,一步到位,牛叉的狠。

    时代在变迁,技术不断进度,代码既要好用,还得优雅。

    目前链式操作的应用在数据库操作上使用的较多,其他方面可自行挖掘。

  • 相关阅读:
    awk使用
    SQL VIEW(视图)
    crontab使用
    SecureCRT
    Python异常
    Python字符串
    Python字典,列表,元组
    Python路径
    vim插件
    Python类
  • 原文地址:https://www.cnblogs.com/fancing/p/6394142.html
Copyright © 2011-2022 走看看