After cross-class call, method cannot be found
方人胥
方人胥 2021-06-12 17:16:18
0
2
896

Exercise of doing static method overloading to implement chained access to the database

demo5.php references the class of Query.php

Then access the method in Query, the page prompts me method' table' was not found in Database

The following is the source code, I hope it can help me check the error

The first one is 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);
    }
}

The second one is 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);
}

方人胥
方人胥

reply all(2)
方人胥

Found the problem, it is line 65 of Query.php. When splicing, spaces should be added before and after FROM.

方人胥

Page prompt method 'table' was not found in Database

image.png

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template