dongying9712 2012-04-28 18:55
浏览 69
已采纳

spl_autoload_register vs __autoload

I try

function some_class($class) {
        require PATH.'test'.$class.'.php';
    }



function test_class($class) {
        require PATH.'some'.$class.'.php';
    }

    spl_autoload_register("test_class");
    spl_autoload_register("some_class");


    $tst = new SomeClass();

SomeClass class locate in "PATH/some/SomeClass.php", but spl_autoload_register call only "test_class" function and not call "some_class". But if I change functions position, then it find new SomeClass.

  • 写回答

3条回答 默认 最新

  • dongwei4096 2012-04-28 19:13
    关注

    Autoload functions are called in sequential order, the first registered function is called first, the second one is called after and so on, until one of them finds the class (unless $prepend is used). If none do, a fatal error is triggered.

    However, in your example, you are using require instead of include, so the first function will always fail with a fatal error if the file doesn't exist, so the second one will never be called. Even if you replace it with include, if both files exist, only the first registered function will be invoked.

    It's a good idea to use file_exists or include when using multiple autoload functions.

    You can also throw exceptions in your autoload functions, so that you can handle undefined classes gracefully instead of killing the script if a class is not found. Per example:

    function my_autoload($class) {
         $filename = "class.{$class}.php";
    
         if (!file_exists($filename))
             throw new Exception("$class not found");
    
         include_once $filename;
    }
    
    spl_autoload_register('my_autoload');
    
    try {
        $a = new Foo;
    } catch (Exception $e) {
        // Foo wasn't found
    }
    
    // continuing the script...
    

    Obviously it depends on your needs, as throwing an exception will halt the execution of subsequent autoload functions.

    Finally, it discouraged to use __autoload at all, spl_autoload_register providing a lot more flexibility that the former.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP