dongyi1159 2012-08-30 22:14
浏览 34

PHP spl_autoload_register什么都不做

i'm updating my code and trying to use spl_autoload_register but IT SIMPLY DOESN'T WORK!!! I'm using PHP 5.3.8 - Apache 2.22 on Centos / Ubuntu / Win7 and trying to echo something but i get nothing instead... have been trying to make it work for the last 3 hours with no result... this is driving me mad!!!

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...!';
    }
}

first echo from __construct works but the "classesAutoloader" doesn't work at all, this class is defined in a php file within a folder and i'm calling it from index.php like follows:

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

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

any help is truly appreciated, thanks in advance!

  • 写回答

2条回答 默认 最新

  • duanjiang7505 2012-08-30 22:21
    关注

    It seems like you're doing the wrong thing. The function that you pass to spl_autoload_register is what's responsible for loading the class file.

    Your code is calling

    $classAuto = new ApplicationInit();
    

    but by that time, ApplicationInit is already loaded so the autoload function doesn't get called

    A more logical way would be for you to to call

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

    Then when you call

    $something = new MyClass();
    

    And the MyClass is not defined, then it will call your function to load that file and define the class.

    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法