php链式操作的实现-php教程

资源魔 24 0

php链式操作的要害是正在做完操作后要return $this;

1、没有应用__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
?>

2、应用__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链式操作的完成的具体内容,更多请存眷资源魔其它相干文章!

标签: php php开发教程 php开发资料 php开发自学

抱歉,评论功能暂时关闭!