PHP培训技术产品
选课中心 APP下载
当前位置:首页 > 技能类 > PHP培训 > 技术产品 > 【技术产品】php链式操作的实现

【技术产品】php链式操作的实现

更新时间:2020-03-19 10:17:09 来源: 阅读量:

【摘要】 对于初入门的php学习者肯定会有很多问题,今天考比过小编为大家整理了关于【技术产品】php链式操作的实现的信息,希望可以帮助到大家。下面就让我们一起来看下【技术产品】php链式操作的实现的具体内容吧!

【技术产品】php链式操作的实现"所谓链式操作最简单的理解就是操作完毕之后再返回对象$this,本文就来为大家介绍一下php链式操作的实现,希望对大家有一定的帮助。",

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链式操作的实现内容,希望可以帮助到你,如果你还有更多关于php的问题,请持续关注考比过php频道,小编会持续为大家分享关于php方面的知识!

分享到: 编辑:admin

技术产品关键词
  • 热门关键词
  • 热门问答