php链式 *** 作的实现

php链式 *** 作的实现,第1张

概述php链式 *** 作的实现

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.jb51.cc/course/list/29/type/2.html

总结

以上是内存溢出为你收集整理的php链式 *** 作的实现全部内容,希望文章能够帮你解决php链式 *** 作的实现所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/997859.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存