PHP试图使用自动加载功能来查找PDO类

时间:2013-07-28 15:44:56

标签: php pdo namespaces autoload

这一直困扰着我一段时间,我似乎无法理解它。

我的phpinfo报告已安装PDO,我可以在index.php文件上连接到我的数据库。但是当我尝试在命名空间类上打开PDO连接时,php正试图使用​​我的自动加载功能来查找无效的PDO.php。

我的课程如下:     

abstract class {

    protected $DB;

    public function __construct()
    {
        try {  
          $this->DB = new PDO("mysql:host=$host;port=$port;dbname=$dbname", $user, $pass);
        }  
        catch(PDOException $e) {  
            echo $e->getMessage();  
        }
    }
}

错误是

Warning: require_once((...)/Model/PDO.php): failed to open stream: No such file or directory in /(...)/Autoloader.php

Fatal error: require_once(): Failed opening required 'vendor/Model/PDO.php' (include_path='.:/Applications/MAMP/bin/php/php5.4.4/lib/php') in /(...)/Autoloader.php

据我所知,应该调用自动加载器,因为安装了PHP PDO扩展(是的,我完全可以肯定)。

我的自动加载如下:

spl_autoload_register('apiv2Autoload');

/**
 * Autoloader
 * 
 * @param string $classname name of class to load
 * 
 * @return boolean
 */
function apiv2Autoload($classname)
{
    if (false !== strpos($classname, '.')) {
        // this was a filename, don't bother
        exit;
    }

    if (preg_match('/[a-zA-Z]+Controller$/', $classname)) {
        include __DIR__ . '/../controllers/' . $classname . '.php';
        return true;
    } elseif (preg_match('/[a-zA-Z]+Mapper$/', $classname)) {
        include __DIR__ . '/../models/' . $classname . '.php';
        return true;
    } elseif (preg_match('/[a-zA-Z]+Model$/', $classname)) {
        include __DIR__ . '/../models/' . $classname . '.php';
        return true;
    } elseif (preg_match('/[a-zA-Z]+View$/', $classname)) {
        include __DIR__ . '/../views/' . $classname . '.php';
        return true;
    }
}

请帮忙吗?

1 个答案:

答案 0 :(得分:15)

它不是真正的自动加载问题。您正尝试在根命名空间上调用类。

通过它看起来你在某个'Model'命名空间并调用PDO,你必须记住默认情况下命名空间是相对的。

你想要的是要么调用绝对路径:

\PDO

或在文件的顶部说你将使用这样的PDO:

use PDO;