php链式操作的关键是在做完操作后要return $this;

一、不使用__call方法实现链式操作

<?phpclass Sql{    private $sql=array("from"=>"",            "where"=>"",            "order"=>"",            "limit"=>"");    public function from($tableName) {        $this->sql["from"]="FROM ".$tableName;        return $this;    }    public function where($_where='1=1') {        $this->sql["where"]="WHERE ".$_where;        return $this;    }    public function order($_order='id DESC') {        $this->sql["order"]="ORDER BY ".$_order;        return $this;    }    public function limit($_limit='30') {        $this->sql["limit"]="LIMIT 0,".$_limit;        return $this;    }    public function select($_select='*') {        return "SELECT ".$_select." ".(implode(" ",$this->sql));    }}$sql =new Sql();echo $sql->from("testTable")->where("id=1")->order("id DESC")->limit(10)->select();//输出 SELECT * FROM testTable WHERE id=1 ORDER BY id DESC LIMIT 0,10?>

二、使用__call方法实现链式操作

__call()在对象调用一个不可访问的方法时会被触发,所以可以实现类的动态方法的创建,实现php的方法重载功能,但它其实是一个语法糖(__construct()方法也是)。

<?phpclass String{    public $value;    public function __construct($str=null)    {        $this->value = $str;    }    public function __call($name, $args)    {        $this->value = call_user_func($name, $this->value, $args[0]);        return $this;    }    public function strlen()    {        return strlen($this->value);    }}$str = new String('01389');echo $str->trim('0')->strlen();// 输出结果为 4;trim('0')后$str为"1389"?>

相关推荐:

PHP视频教程:https://www.php.cn/course/list/29/type/2.html

更多相关文章

  1. PHP常用日期时间操作合集
  2. 神操作之实现PHP跳转
  3. Mysqli的基本操作-CURD的学习开发总结
  4. PHP中一些常用操作类代码解析
  5. 最全的php数组操作方法汇总,让你轻松掌握!
  6. PHP 简单实现延时操作
  7. 详解PHP使用gearman进行异步的邮件或短信发送操作
  8. PHP如何操作json?方法介绍
  9. PHP与Web页面交互操作实例解析

随机推荐

  1. 如何实现对Android设备进行文本的模拟输
  2. 【Android(安卓)电量优化】电量优化 ( 充
  3. 仿微信备注 editext下划线
  4. [Android遊戲] 森林跑跑熊:iOS移植的殺時
  5. Android应用程序目录结构分析
  6. android中使用线程(比如修改textview的tex
  7. Go support for Android
  8. Android,GridLayout布局(简易计算器)
  9. Android 线程池来管理线程
  10. Android 组件属性