我是PHP命名空间的新手。当我使用自动加载时出现问题。
ROOT/Application/Instance.php
<?php
namespace Application;
class Instance {
public static $_database;
public function __construct() {
self::$_database = new \Application\Module\Database();
}
public static function database() {
return self::$_database;
}
public static function ID(){
return md5(uniqid(mt_rand(), TRUE) . mt_rand() . uniqid(mt_rand(), TRUE));
}
public static function autoload($_className) {
$thisClass = str_replace(__NAMESPACE__.'\\', '', __CLASS__);
$baseDir = __DIR__;
if (substr($baseDir, -strlen($thisClass)) === $thisClass) {
$baseDir = substr($baseDir, 0, -strlen($thisClass));
}
$_className = ltrim($_className, '\\');
$fileName = $baseDir;
$namespace = '';
if ($lastNsPos = strripos($_className, '\\')) {
$namespace = substr($_className, 0, $lastNsPos);
$_className = substr($_className, $lastNsPos + 1);
$fileName .= str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $_className) . '.php';
if (file_exists($fileName)) {
require $fileName;
}
}
public static function registerAutoloader() {
spl_autoload_register(__NAMESPACE__ . "\\Instance::autoload");
}
}
ROOT/Application/Module/Database.php
<?php
namespace Application\Module;
include 'FluentPDO/FluentPDO.php';
class Database extends Module {
public static $_instance;
public function __construct() {
if(self::$_instance === NULL) {
self::$_instance = new FluentPDO(new PDO("mysql:host=8273639.mysql.rds.aliyuncs.com;dbname=db", 'name', 'password'));
}
}
}
当我运行时:
new \Application\Instance();
我收到了这个错误:
Fatal error: Class 'Application\Module\FluentPDO' not found in /mnt/www/airteams_com/public/Application/Module/Database.php on line 13
我很确定'FluentPDO/FluentPDO.php'
存在。并且错误显示文件的错误路径。正确的路径是'ROOT/Application/Module/FluentPDO/FluentPDO.php'
那么在我的情况下如何使用no namespace类呢?感谢。
答案 0 :(得分:1)
当您使用命名空间时,除非它是当前命名空间的子节点,否则您必须完全限定每个类。
因此,FluentPDO可能位于根命名空间,这意味着您需要像这样访问它:
self::$_instance = new \FluentPDO(new \PDO("mysql:host=8273639.mysql.rds.aliyuncs.com;dbname=db", 'name', 'password'));