我面临一个问题,我不幸无法解决.我创建了一个数据库类到app / db /
mysql / database.php,具有以下内容:
<?php namespace App\Database; use Symfony\Component\Yaml\Yaml; class Database{ private static $connection = null; private function __construct( $host,$base,$user,$pass ){ try{ self::$connection = new PDO("mysql:host=$host;dbname=$base",$pass); }catch(PDOException $e){ die($e->getMessage()); } } public static function get(){ if( self::$connection !== null ){ return self::$connection; } $yaml = Yaml::parse(file_get_contents(realpath('./app') . '/database.yml')); self::$connection = new Database( $yaml['host'],$yaml['base'],$yaml['user'],$yaml['pass'] ); } }
使用作曲家,我自动加载这个类:
{ "autoload" : { "classmap" : [ "app/libraries","app/db" ] } }
其中生成一个autoload_classmap.php,如:
return array( 'App\\Database\\Database' => $baseDir . '/app/db/mysql/database.php','App\\Libraries\\Parser' => $baseDir . '/app/libraries/Parser.php',);
现在,一切正常,我总是会遇到与PDO有关的错误:
Fatal error: Class 'App\Database\PDO' not found in /var/www/my_application/app/db/mysql/database.php on line 24
我认为问题来自于命名空间,因为当我将类放入索引页面时,我没有任何错误. PDO已安装并工作.
问题已经被编辑了,但是对于那些只是直接回答答案的人来说,这是..
您应该为方法中的对象使用正确的命名空间,或者使用它们或使用根命名空间前缀;
<?php //... namespace etc... use \PDO; self::$connection = new PDO("mysql:host=$host;dbname=$base",$pass);
或简单地
self::$connection = new \PDO("mysql:host=$host;dbname=$base",$pass);