【发布时间】:2012-05-11 16:17:16
【问题描述】:
我一直在研究不同的框架以及它们如何实现类的自动加载,但我是 PHP 新手,所以不确定我是否正确解释了它的函数。我试图创建自己的类,仅使用它来自动加载我的所有类,无法访问这些类。这是我的代码的样子:
class Autoloader {
private $map = array();
private $directories = array();
public function register() {
spl_autoload_register(array($this, 'load'));
}
public function unregister() {
spl_autoload_unregister(array($this, 'load'));
}
public function map($files) {
$this->map = array_merge($this->map, $files);
$this->load($this->map);
}
public function directory($folder) {
$this->directories = array_merge($this->directories, $folder);
}
public function load($class) {
if ($file = $this->find($class)) {
require $file;
}
}
public function find($file) {
foreach ($this->directories as $path) {
if (file_exists($path . $file . '.php')) {
return $path . $file . '.php';
}
}
}
}
我像这样从我的引导文件中加载类
require('classes/autoload.php');
$autoload = new Autoloader();
$autoload->map(array(
'Config' => 'classes/config.php',
'Sql' => 'classes/db.php'
));
$autoload->directory(array(
'classes/'
));
$autoload->register();
然后我尝试实例化已映射的类之一
$sql = new SQL($dbinfo);
$sql->query($query);
我所做的有什么问题,我做对了吗?我基本上希望自动加载类从引导文件映射一组类,并在它们被调用/实例化时包含这些文件,并在它们不再使用时停止包含它们。
【问题讨论】:
-
您正在调用 $autoload->map 并使用数组作为参数。 map 本身用一个数组调用 load,这似乎需要一个字符串?
-
你有没有跟着代码执行看它是否真的包含一个类?添加一些 echo 语句,看看会发生什么
-
另外,尝试在加载函数中添加调试 echo / var_dump / die 以查看 spl_autoload_register 是否真的导致函数被调用并回显 $file。
-
你在
$this->map()之后又在哪里使用$this->map?
标签: php oop class autoloader