PHP实现无顺序连贯操作

想必大家都用过tp的Db类吧,连贯操作是不是很酷

实现很简单不需要用到__call方法

简单分析一下tp框架的Db类

1
Db::name('user')->where('id', 1)->find()

以上这行代码 首先调用name方法不过是静态的最后返回当前对象继续调用其他方法

重点:结束时是return当前对象,静态方法使用 return new self() 返回,非静态使用 return $this;

下面举一个小例子:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
    /**
     * @author anderyly
     * @email anderyly@sina.com
     * @link https://blog.aaayun.cc
     * @copyright Copyright (c) 2019
     */

    namespace ay;

    class Test {

        public static $name;
    
        public static function set($name) {
            self::$name = $name;
            return new self();
        }
    
        public function add() {
            self::$name = "an" . self::$name;
            return $this;
        }
    
        public function get() {
            return self::$name;
        }
    
    
    }

调用Test类

1
2
3
$name = Test::set('deryly')->add()->get();
    echo $name;
    // 输出 anderyly
Licensed under CC BY-NC-SA 4.0
最后更新于 Aug 15, 2025 15:01 +0800