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 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘