0

我正在更新我的代码并尝试使用 spl_autoload_register 但它根本不起作用!!!我在 Centos / Ubuntu / Win7 上使用 PHP 5.3.8 - Apache 2.22 并试图回应一些东西,但我什么也没得到......一直试图让它在过去 3 个小时内工作但没有结果......这是快把我逼疯了!!!

class ApplicationInit {
    // Constructor
    public function __construct() {
        spl_autoload_register(array($this, 'classesAutoloader'));
        echo 'construct working...!';
    }

    // Autoloading methods
    public function classesAutoloader($class) {
        include 'library/' . $class . '.php';

        echo 'autoload working...!';
    }
}

来自 __construct 的第一个回显有效,但“classesAutoloader”根本不起作用,此类定义在文件夹内的 php 文件中,我从 index.php 调用它,如下所示:

define('DS', DIRECTORY_SEPARATOR);
define('ROOT', getcwd() . DS);
define('APP', ROOT . 'application' . DS);

// Initializing application
require(APP.'appInit.php');
$classAuto = new ApplicationInit();

任何帮助都非常感谢,在此先感谢!

4

2 回答 2

1

好像你在做错事。您传递给的函数spl_autoload_register负责加载类文件。

您的代码正在调用

$classAuto = new ApplicationInit();

但是到那时,ApplicationInit已经加载了,所以不会调用自动加载函数

一个更合乎逻辑的方式是让你打电话

spl_autoload_register(function($class){
    include 'library/' . $class . '.php';
});

然后当你打电话

$something = new MyClass();

并且MyClass未定义,然后它将调用您的函数来加载该文件并定义类。

于 2012-08-30T22:21:29.637 回答
1

你有什么问题?您的代码工作正常。

class ApplicationInit {
    public function __construct() {
        spl_autoload_register(array($this, 'classesAutoloader'));
        echo 'construct working...!';
    }

    public function classesAutoloader($class) {
        include 'library/' . $class . '.php';

        echo 'autoload working...!';
    }
}

$classAuto = new ApplicationInit(); //class already loaded so dont run autoload

$newclass = new testClass(); //class not loaded so run autoload
于 2012-08-31T08:03:56.197 回答