登录  /  注册
博主信息
博文 42
粉丝 0
评论 0
访问量 34977
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
链式调用和方法重载原理
庆选的博客
原创
612人浏览过

链式调用:即是每次访问方法,返回当前类实例, 用来链式调用后面的其它方法

方法重载:

query.php

实例

<?php


namespace _1008;

// 数据库查询类
class Query
{
    // 连接对象
    public $pdo = null;

    // 表名
    public $table;

    // 字段
    public $field = '*';

    // 条件
    public $where;

    // 数量
    public $limit;

    // 构造方法
    public function __construct($pdo)
    {
        // 实例时自动连接数据库
        $this->pdo = $pdo;
    }

    // 设置数据表名称
    public function table($tableName)
    {
        $this->table = $tableName;
        //返回当前类实例, 用来链式调用后面的其它方法
        return $this;
    }

    // 设置数据表字段
    public function field($fields = '*')
    {
        $this->field = empty($fields) ? '*' : $fields;
        return $this;
    }

    // 设置查询条件
    public function where($where = '')
    {
        $this->where = empty($where) ? $where : ' WHERE '. $where;
        return $this;
    }

    // 设置显示数量
    public function limit($limit)
    {
        $this->limit = empty($limit) ? $limit : ' LIMIT '. $limit;
        return $this;
    }

    // 生成SQL语句
    public function select()
    {

//        SELECT * FROM table WHERE **** LIMIT n

        // 拼装SQL
        $sql = 'SELECT '
            . $this->field // 字段列表
            . ' FROM '
            . $this->table  // 数据表
            . $this->where  // 条件
            . $this->limit;  // 显示数量

        // 预处理
        $stmt = $this->pdo->prepare($sql);
            $stmt->execute();
//        die($stmt->debugDumpParams());  // 查看生成的sql

        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

}

运行实例 »

点击 "运行实例" 按钮查看在线实例

实现

实例

<?php
namespace _1008;

require 'Query.php';

class DB
{
    // 连接对象
    protected static $pdo = null;

    // 数据库的连接方法
    public static function connection()
    {
        self::$pdo = new \PDO('mysql:host=127.0.0.1;dbname=php', 'root', 'root');
    }

    public static function __callStatic($name, $arguments)
    {
       // 连接数据库
        self::connection();
        // 实例化查询类,将连接对象做为参数
        $query = new Query(self::$pdo);
        // 调用查询对象$query中的对应的方法
        return call_user_func_array([$query, $name],$arguments);
    }
}

$staffs = DB::table('staff')
    ->field('staff_id,name,position,mobile')
    ->where('staff_id > 2')
    ->limit(5)
    ->select();

// 遍历
foreach ($staffs as $staff) {
    print_r($staff); echo '<br>';
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学