跨类调用后,找不到方法
方人胥
方人胥 2021-06-12 17:16:18
0
2
684

做静态方法重载实现数据库的链式访问的练习

demo5.php引用了Query.php的类

然后访问Query中的方法,页面提示我方法 'table' 在 Database 中未找到

以下是源代码,希望可以帮我检查出错误

第一个是Query.php

<?php
//常用的数据查询操作
class Query
{
    //连接对象
    public $pdo = null;

    //数据表名称
    public $table = '';

    //字段列表
    public $field = '';

    //查询条件
    public $where = '';

    //显示数量
    public $limit = 0;


    //构造方法
    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    //调用表名
    public function table($tableName)
    {
        $this->table = $tableName;
        //关键是这一步
        return $this;
    }

    //调用字段
    public function field($fields)
    {
        $this->field = $fields;
        //关键是这一步
        return $this;
    }

    //设置查询条件
    public function where($where)
    {
        $this->where = $where;
        return $this;
    }
    //设置显示数量
    public function limit($limit)
    {
        $this->limit = $limit;
        return $this;
    }

    //创建SQL语句查询
    public function select()
    {
        //设置查询条件
        $fields = empty($this->field) ? '*' : $this->field;
        $where = empty($this->where) ? '' : ' WHERE ' . $this->where;
        $limit = empty($this->limit) ? '' : ' LIMIT ' . $this->limit;

        //SQL
        $sql = 'SELECT '.$fields. 'FROM' .$this->table. $where . $limit;

        //预处理执行
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

第二个是demo5.php

<?php
//方法重载实例演示
require 'Query.php';
class Database
{
    //数据库连接对象
    protected static $pdo = null;

    //数据库连接方法,每次查询时再连接,实现真正的惰性连接,节省系统开销
    public static function connection()
    {
        self::$pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','admin');
    }

    //静态方法的重载,实现跨类调用
    public static function __callStatic($name,$arguments)
    {
        //连接上数据库
        self::connection();

        //实例化查询类
        $query = new Query(self::$pdo);

        //访问Query中的方法
        return call_user_func_array([$query, $name],[$arguments[0]]);
    }


}

$cats = Database::table('category')
    ->field('cate_id, name, alias')
    ->where('cate_id>=2')
    ->select();

foreach($cats as $cat){
    print_r($cat);
}

方人胥
方人胥

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!