当前位置: 移动技术网 > IT编程>开发语言>PHP > php链式操作的实现

php链式操作的实现

2020年03月18日  | 移动技术网IT编程  | 我要评论

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链式操作的实现的详细内容

更多内容请访问

怎么从一名码农成为架构师的必看知识点:目录大全(持续更新)50w年薪挑战!

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网