找不到 PHP 命名空间 PDO
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19699319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP namespace PDO not found
提问by lkartono
I'm facing an issue I unfortunatly could not resolve so far. I created a database class
into app/db/mysql/database.php
with the following content :
我正面临一个我很遗憾目前无法解决的问题。我创建了一个database class
到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", $user, $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'] );
}
}
Using composer, I'm autoloading this class :
使用作曲家,我正在自动加载这个类:
{
"autoload" : {
"classmap" : [
"app/libraries",
"app/db"
]
}
}
Which generate an autoload_classmap.php
such as :
其中生成一个autoload_classmap.php
如:
return array(
'App\Database\Database' => $baseDir . '/app/db/mysql/database.php',
'App\Libraries\Parser' => $baseDir . '/app/libraries/Parser.php',
);
Now, when everything works fine, I'm always getting an error related to PDO :
现在,当一切正常时,我总是收到与 PDO 相关的错误:
Fatal error: Class 'App\Database\PDO' not found in /var/www/my_application/app/db/mysql/database.php on line 24
I think the problem comes from namespace
because when I put the class into the index page, I don't have any error. PDO is installed and works.
我认为问题来自于namespace
当我将类放入索引页面时,我没有任何错误。PDO 已安装并运行。
回答by wtfzdotnet
Question was already edited, but for people who are just heading straight over to the answers, here it is..
问题已被编辑,但对于那些直接转向答案的人来说,这里是..
You should be using correct namespaces for the objects in your methods, either "use" them or prefix them with the root namespace;
您应该为方法中的对象使用正确的命名空间,要么“使用”它们,要么用根命名空间作为前缀;
<?php
//... namespace etc...
use \PDO;
self::$connection = new PDO("mysql:host=$host;dbname=$base", $user, $pass);
or simply;
或者干脆;
self::$connection = new \PDO("mysql:host=$host;dbname=$base", $user, $pass);