温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

php链式操作的实现方法

发布时间:2020-03-20 17:00:36 来源:亿速云 阅读:206 作者:小新 栏目:编程语言

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链式操作的实现方法的详细内容,如果想了解更多请关注亿速云其它相关文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI