这已经困扰我一段时间了,我似乎无法理解它。
我的 phpinfo 报告 PDO 已安装,我可以连接到我的 index.php 文件上的数据库。但是,当我尝试在命名空间类上打开 PDO 连接时,php 正在尝试使用我的自动加载函数来查找 PDO.php,但这是行不通的。
我的类(class)如下:
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;
}
}
有什么帮助吗?
最佳答案
这不是真正的自动加载问题。您正在尝试调用根命名空间上的类。
从外观上看,您在某个“模型”命名空间中并正在调用 PDO
,您必须记住 namespaces are relative by default .
你想要的是调用绝对路径:
\PDO
或者在你的文件的顶部说你将像这样使用 PDO:
use PDO;
关于PHP 试图使用自动加载功能来查找 PDO 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17909966/