PDO, PHP:试图实例化对象来调用函数-空白页


PDO, PHP: Trying to instantiate object to call function - blank page

这个问题涉及到两个文件。其中一个是数据库类,另一个是include_once数据库文件的文件,然后继续实例化该类的对象以调用函数——getDB();。这就是问题所在。

数据库类:

<?php
  class Database {           
    private static $datasource='mysql:host=localhost; dbname=db_name';
    private static $username='root';
    private static $password='root';
    private static $db;      
    private function __construct(){}
    public static function getDB(){ 
      if(!isset(self::$db)){ 
        try{
          self::$db=new PDO(self::$datasource,self::$username,self::$password); 
        }
        catch(PDOExceptin $e) {
          $error=$e->getMessage(); //variable $error can be used in the database_error.php file 
          //display database error file.  
          //include('database_error.php');
          exit();            
        }
      }
      return self::$db;      
    }
    function Database(){
      return new Database;
    }
  }
  ?>

在我的主文件中,我这样做:

 <?php
    include('partials/header.php'); 
    include_once('functions/pdo.php');
    $database = new Database();
    $getdb = $database->getDB();
    //Anything below won't show because of the failed instantiation of Database object above.
    //code..
 ?>

显然,我在这里做错了什么。我用php 5.3运行MAMP。我怎样才能正确使用我的数据库?我有一个与类同名的函数的原因是因为我读到你可以用函数来实例化对象,但我也没有让它工作…

这里有一些错误(使用ini_set("display_errors", 1); error_reporting(-1);查看所有错误消息):

PDO异常类命名为PDOException,不命名为PDOExceptin

从非静态上下文中调用静态函数:$database->getDb(),其中getDb是静态方法。(写Database::getDb())

您编写new Database将导致致命错误,因为构造函数是私有的(并且命名构造函数的优先级低于魔术方法)。使用:

$getdb = Database::Database(); // and declare your Database method as static

PDOExceptin应该是PDOException

此外,它有助于打开display_errors并在开发时安装xdebug。

很明显,我做错了什么。

是的。你写的代码太多了。
您编写的代码越多,错误就越多。所以,去掉所有无用的代码:

class Database {           
    private static $datasource='mysql:host=localhost; dbname=db_name';
    private static $username='root';
    private static $password='root';
    private static $db;      
    public static function getDB(){ 
      if(!isset(self::$db)){ 
          self::$db=new PDO(self::$datasource,self::$username,self::$password); 
      }
      return self::$db;      
    }
}

,这样命名

$db = Database::getDB();