Php 为什么我会得到';在null';上调用成员函数prepare();何时加载pdo?

Php 为什么我会得到';在null';上调用成员函数prepare();何时加载pdo?,php,Php,在将pdo实例传递到类方法中时,我遇到了这个错误(“未捕获错误:对null上的成员函数prepare()的调用”)。selectAll方法引发该错误。堆栈跟踪为#0。我不明白为什么我会犯这个错误 class QueryBuilder { protected $pdo; protected $newTask; public function __construct($pdo) { $this->pdo = $pdo; } //Selects from table and

在将pdo实例传递到类方法中时,我遇到了这个错误(“未捕获错误:对null上的成员函数prepare()的调用”)。selectAll方法引发该错误。堆栈跟踪为#0。我不明白为什么我会犯这个错误

class QueryBuilder {


protected $pdo; 

protected $newTask;

public function __construct($pdo) {

  $this->pdo = $pdo; 
}

//Selects from table and returns to view

public function selectAll($table, $intoClass) {

  $stmt = $this->pdo->prepare("select * from {$table} limit 1, 9"); 
  $stmt->execute(); 
  return $stmt->fetchAll(PDO::FETCH_CLASS, $intoClass); 

}

//Adds a new task to the table

public function addToTable($table, $newTask) {

    $done = 0; 

          try {
    $stmt = $this->pdo->prepare("insert into {$table} (description, completed) values (:todo, :done)");
    $stmt->bindParam(':todo', $newTask);
    $stmt->bindParam(':done', $done); 
    $stmt->execute(); 
    } catch(PDOException $e) {
       die($e->getMessage()); 
    }

}

}
这是index.php文件,我在其中保存了pdo变量

error_reporting(E_ALL);
ini_set('display_errors', '1');

require "Task.php"; 
require "config.php"; 
require "connection.php"; 
require "QueryBuilder.php"; 

$pdo = Connection::make(); 

$query = new QueryBuilder($pdo); 

$tasks = $query->selectAll('todos', 'Task'); 

$newTask = $_POST['todo']; 

require 'user.view.php'; 
php是我初始化pdo的地方

 class Connection { 

  public static function make() {

     try {
    $pdo = new PDO('mysql:host=127.0.0.1;dbname=mytodo', 'root', ' 
', array(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION));
 } catch (PDOException $e) {
     die ($e->getMessage()); 
 }

    }

 }

您正在创建的连接是您正在调用的静态函数的返回值:

$pdo = Connection::make();
但该函数不返回任何内容,使该连接对象
null

public static function make() {
    try {
        $pdo = new PDO('mysql:host=127.0.0.1;dbname=mytodo', 'root', ' ', array(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION));
    } catch (PDOException $e) {
        die ($e->getMessage()); 
    }
}
从函数返回连接对象:

public static function make() {
    try {
        return new PDO('mysql:host=127.0.0.1;dbname=mytodo', 'root', ' ', array(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION));
    } catch (PDOException $e) {
        die ($e->getMessage()); 
    }
}

您正在创建的连接是您正在调用的静态函数的返回值:

$pdo = Connection::make();
但该函数不返回任何内容,使该连接对象
null

public static function make() {
    try {
        $pdo = new PDO('mysql:host=127.0.0.1;dbname=mytodo', 'root', ' ', array(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION));
    } catch (PDOException $e) {
        die ($e->getMessage()); 
    }
}
从函数返回连接对象:

public static function make() {
    try {
        return new PDO('mysql:host=127.0.0.1;dbname=mytodo', 'root', ' ', array(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION));
    } catch (PDOException $e) {
        die ($e->getMessage()); 
    }
}