phpspl-autoload-registerspl-autoloader

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;
}

Solution

  • 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)