【问题标题】:Autoloading a class once class is called from an array using PHP使用 PHP 从数组中调用类后自动加载类
【发布时间】: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


【解决方案1】:

您的课程似乎被称为Config,您的文件似乎被称为config(注意区分大小写)。

猜测"classes/Config.php" 的 file_exists 失败。

你现在根本没有使用你的地图。

【讨论】:

    【解决方案2】:

    我认为问题出在这一行 - $this->map = array_merge($this->map, $files) 因为您将 $files 传递给 $autoload->map() 作为 Array,但您试图在 find() 方法中获取 String 的值.

    【讨论】:

    • 好的,所以我刚刚尝试更改加载类,以便它只需要合并的数组而不是将值作为字符串查找,但它会抛出错误“非法偏移类型”并且函数完全失败抓取单个文件,因此不能包含任何内容(“需要打开失败”)。加载函数现在看起来像这样:public function load($class) { if (isset($this->map[$class])) { require $this->map[$class]; } }
    【解决方案3】:

    您的“地图”功能似乎有些奇怪。

    当 map 被调用时,它传递一个数组来加载,但是加载函数似乎期望 $class 在 find 函数中使用,就好像它是一个字符串一样!

    我认为你需要再看看你是如何调用你的函数并跟踪在哪里使用了哪些参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-08
      • 1970-01-01
      相关资源
      最近更新 更多