2015-04-07 75 views
0

我是PHP编程中尝试使用PDO连接到数据库的新手。但在做收到错误为:无法使用PDO连接到数据库

"Class 'DB' not found in D:\xampp\htdocs\web\oop\index.php on line 5"

请帮助“信息中给出的打击提前感谢

的config.php

<?php 
    class Config{ 
    public static function get($path = null) 
    { 
    if($path){ 
     $config = $GLOBALS['config']; 
     $path = explode('/', $path); 

     foreach($path as $bit) 
     { 
      if(isset($config[$bit])) 
      { 
       $config = $config[$bit]; 
      } 
     } 
     return $config; 
    } 
      } 
     } 
     ?> 

核心/的init.php

 require_once 'functions/sanitize.php'; 

    $GLOBALS['config'] = array(
    'mysql' => array(
    'host'=> '127.0.0.1', 
    'username' => 'root', 
    'password' => '', 
    'db' => 'oop' 
    ), 
'remember' => array(
    'cookie_name' => 'hash', 
    'cookie_expiry' => 604800 
    ), 
'session' => array(
    'session_name' => 'user' 
    ) 
); 


    spl_autoload_register(function($class) 
    { 

require_once 'classes/' . $class . '.php'; 
} 
    ) 


?> 

类/ db.php中

 <?php 
    namespace application\libs; 
    use POD; 
    class DB 
    { 

     private static $_instance = null; 
     private $_pdo, 
       $_query, 
       $_error = false, 
       $_results, 
       $_count = 0; 


     private function __construct() 
     { 
      try{ 
       $this->_pdo = new POD('mysql:host=' . 
       Config::get('mysql/host') . ';dbname=' . 
       Config::get('mysql/db'), Config::get('mysql/username'), 
        Config::get('mysql/password')); 
      }catch(PDOException $e){ 
       die($e->getMessage()); 

      } 
     } 


     public static function getInstance() 
     { 
      if(!isset(self::$_instance)){ 
       self::$_instance = new DB(); 
      } 

      return self::$_instance; 
     } 


    } 



    ?> 

的index.php

<?php 
     require_once 'core/init.php'; 
     DB::getInstance(); 
    ?> 
+1

尝试 \ application \ libs \ DB :: getInstance(); –

+0

尝试$ this - > _ pdo = new POD('mysql:host ='。Config :: get('mysql/host')。'; username ='。Config :: get('mysql/username')。';口令=”配置::得到。( 'MySQL的/口令')。 '; DBNAME ='(MySQL的/分贝 ')。 '配置::得到。';'); –

+0

看起来你的自动加载器找不到你的类,你需要尝试和调试自动加载部分,尝试回显你正在获得的'$ class'参数,并看看它到达的路径 – Fadey

回答

0

看起来你对你的自动加载类的路径是错误的,请尝试以下方法:

spl_autoload_register(function($class) 
    { 

require_once '/../classes/' . $class . '.php'; 
} 
    ) 

或者在请求文件时请使用绝对路径,这将始终确保您的文件将加载。

spl_autoload_register(function($class) 
    { 

require_once __DIR__ .'/classes/' . $class . '.php'; 
} 
    ) 
+0

您好Fadey感谢您的答复,但第一个答复获得与”Class'DB'相同的错误D:\ xampp \ htdocs \ web \ oop \ index.php在第5行“,第二个回复得到另一个重大错误,如果你能给出更好的想法,这将是非常友善的。 – Tapash

+0

@Tapash在你需要它之​​前你应该知道文件的确切位置,如果你不知道你的项目结构,我不能真正帮助你,所以你要么向我们展示你的结构,要么试图找出你自己的结构类 – Fadey