简体   繁体   中英

PHP spl_autoload: how to determine the autoload function requestor

Is there a way for the function registered by spl_autoload_register to know the source file/class/method that's calling it? I want to be able to output a useful error when a class is not found so I know which source file needs to be updated. For example:

spl_autoload_register(function($className)
{
    $classFile = 'include/' . $className . '.php';
    if (!is_readable($classFile))
    {
        echo 'Could not load ' . $className . ' requested by ' . $source; 
        // how to figure out $source -----------------------------^^
        return false;
    }

    include $classFile;
    return false;
}

That's what a stack trace does. It shows you the chain of events that lead to your error (and can provide details like class, line number, etc)

Try var dumping debug_backtrace() to see the array it returns and if it can helps.

spl_autoload_register(function($className)
{
    var_dump(debug_backtrace());

    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM