"","order"=>"","limit"=>"");public function from($tableName) {$this->sql["from"]="FROM ".$tableName;return $this;}public function where($_where=1=1) " />

百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>网页制作> php链式操纵的实现
分享文章到:

php链式操纵的实现

发布时间:09/01 来源:未知 浏览: 关键词:

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

一、不使用__call办法实现链式操纵

<?php
class 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()办法也是)。

<?php
class 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

以上就是php链式操纵的实现的具体内容,更多请关注百分百源码网其它相关文章!

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有152人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板