栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP

php链式操作的实现

PHP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力


php链式操作的实现

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

一、不使用__call方法实现链式操作

"",
     "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()方法也是)。

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链式操作的实现的详细内容,更多请关注考高分网其它相关文章!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/263237.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号