因此,我已经开始使用名称空间,并阅读了一些文档,但我似乎做错了什么。
首先是我的应用程序结构,它是这样构建的:
root
-dashboard(this is where i want to use the autoloader)
-index.php
--config(includes the autoloader)
--WePack(package)
---src(includes all my classes)现在,在src目录中,我包含了以下类:
namespace WePack\src;
class Someclass(){
}config.php的内容如下:
<?php
// Start de sessie
ob_start();
session_start();
// Locate application path
define('ROOT', dirname(dirname(__FILE__)));
set_include_path(ROOT);
spl_autoload_extensions(".php"); // comma-separated list
spl_autoload_register();
echo get_include_path();我像这样在我的index.php里用它
require_once ('config/config.php');
use WePack\src;
$someclass = new Someclass;这是echo get_include_path();返回的内容:
/home/wepack/public_html/dashboard我猜这就是我想要的。但是这些类没有加载,也没有发生任何事情。我显然遗漏了什么,但我似乎搞不清楚。你们能看看然后向我解释一下为什么这不管用吗?
发布于 2015-03-02 10:15:02
这里的问题是,您没有向spl_autoload_register()注册回调函数。看看官方的文档。
为了更灵活,您可以编写自己的类来注册和自动注册类,如下所示:
class Autoloader
{
private $baseDir = null;
private function __construct($baseDir = null)
{
if ($baseDir === null) {
$this->baseDir = dirname(__FILE__);
} else {
$this->baseDir = rtrim($baseDir, '');
}
}
public static function register($baseDir = null)
{
//create an instance of the autoloader
$loader = new self($baseDir);
//register your own autoloader, which is contained in this class
spl_autoload_register(array($loader, 'autoload'));
return $loader;
}
private function autoload($class)
{
if ($class[0] === '\\') {
$class = substr($class, 1);
}
//if you want you can check if the autoloader is responsible for a specific namespace
if (strpos($class, 'yourNameSpace') !== 0) {
return;
}
//replace backslashes from the namespace with a normal directory separator
$file = sprintf('%s/%s.php', $this->baseDir, str_replace('\\', DIRECTORY_SEPARATOR, $class));
//include your file
if (is_file($file)) {
require_once($file);
}
}
}在此之后,您将注册您的自动加载器如下:
Autoloader::register("/your/path/to/your/libraries");发布于 2015-03-02 10:20:00
这不是你的意思吗
spl_autoload_register(function( $class ) {
include_once ROOT.'/classes/'.$class.'.php';
});这样,您就可以调用这样的类:
$user = new User(); // And loads it from "ROOT"/classes/User.phphttps://stackoverflow.com/questions/28739392
复制相似问题