本文介绍了PHP尝试使用自动加载功能查找PDO类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这已经困扰了我一段时间了,我似乎无法理解.

This has been bugging me for some time now and I can't seem to make sense of it.

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

My phpinfo reports that PDO is installed and I can connect to my database on my index.php file. But when I try to open a PDO connection on a namespaced class, php is trying to use my autoload function to find PDO.php which won't work.

我的课程如下:

My class is as follows:

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扩展(是的,我完全确定).

As far I as know the autoloader should be called because PHP PDO extension is installed (yes I'm completely sure).

我的自动加载如下:

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

请帮忙吗?

推荐答案

这并不是真正的自动加载问题.您正在尝试在根名称空间上调用一个类.

Its not really an autoload issue. You are attempting to call a class on the root namespace.

从外观上看,您在某些模型"名称空间中并调用PDO,您必须记住默认情况下名称空间是相对的.

By the looks of it your are in some 'Model' namespace and calling PDO, you must remember that namespaces are relative by default.

您想要的就是调用绝对路径:

What you want is to either call the the absolute path:

\PDO

或在文件顶部说您将像这样使用PDO:

or at the top of your file say you're going to use PDO like this:

use PDO;

这篇关于PHP尝试使用自动加载功能查找PDO类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 07:55