【问题标题】:spl_autoload not calling second autoload functionspl_autoload 不调用第二个自动加载函数
【发布时间】:2011-10-07 04:36:13
【问题描述】:

我调用了一个 spl_autoload,但问题是第二个自动加载没有执行,我不知道为什么。使用此代码,此代码脚本应该死掉。我从文件夹数组中删除类,自动加载将起作用。我的代码如下所示:

<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors','On'); 
/*** nullify any existing autoloads ***/
spl_autoload_register(null, false);
/*** specify extensions that may be loaded ***/
spl_autoload_extensions('.php');

function dataLoader($class) {
    foreach (array(PV_CORE.DS.'data'.DS, PV_CORE.DS.'system'.DS, PV_CORE.DS.'cms'.DS, PV_CORE.DS.'util'.DS,PV_CORE.DS.'components'.DS, PV_CORE.DS.'template'.DS) as $folder){
        if (is_file($folder.$class.'.php')) {
            include_once $folder.$class.'.php';
        }
    }//end foreach
}

function testLoader($class) {
    die();
    $filename = $class. '.php';
    $file =PV_CORE.DS.'data'.DS.$filename;
    if (!file_exists($file)) {
        return false;
    }
    require_once $file;
}

spl_autoload_register('dataLoader');
spl_autoload_register('testLoader');

【问题讨论】:

  • 你的函数是寄存器:print_r(spl_autoload_functions());我真的不明白你想做什么。

标签: php spl


【解决方案1】:

您的代码有效,但可能是一个误解。

您的函数已注册:

print_r( spl_autoload_functions() );

返回:

Array
(
    [0] => dataLoader
    [1] => testLoader
)

如果你初始化一个类

$class_obj = new ClassName();

dataLoader 将尝试加载文件:

$folder.ClassName.php

如果他首先找不到类,您的脚本只会加载第二个或任何其他注册的函数。

因此,如果您在函数 dataLoader 中删除 $class __autoload 将不会再在第一个注册函数中找到该类,因此他将尝试在第二个注册函数中查找它,依此类推。

【讨论】:

  • 是的,我假设 spl_autoload 正在加载所有关闭,但是当找不到类时它会按需加载。
【解决方案2】:

你需要

返回真; // 如果类已加载并且您希望自动加载堆栈将停止

返回假; // 如果类还没有加载,你想继续执行自动加载堆栈

在你的回调中

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2013-12-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-30
    • 1970-01-01
    相关资源
    最近更新 更多