找不到PHP名称空间PDO [英] PHP namespace PDO not found

查看:115
本文介绍了找不到PHP名称空间PDO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临的问题是我迄今为止无法解决的.我在app/db/mysql/database.php中创建了一个database class,其内容如下:

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 :

<?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"
        ]
    }
}

会生成autoload_classmap.php,例如:

return array(
    'App\\Database\\Database' => $baseDir . '/app/db/mysql/database.php',
    'App\\Libraries\\Parser' => $baseDir . '/app/libraries/Parser.php',
);

现在,当一切正常时,我总是收到与PDO相关的错误:

Now, when everything works fine, I'm always getting an error related to PDO :

Fatal error: Class 'App\Database\PDO' not found in /var/www/my_application/app/db/mysql/database.php on line 24

我认为问题出在namespace,因为当我将类放入索引页面时,我没有任何错误. PDO已安装并正常工作.

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.

推荐答案

问题已经过编辑,但是对于那些直接回答问题的人来说,就在这里.

您应该为方法中的对象使用正确的名称空间,或者使用"它们或为它们添加根名称空间;

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);

或简单地

self::$connection = new \PDO("mysql:host=$host;dbname=$base", $user, $pass);

这篇关于找不到PHP名称空间PDO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆