Question

Is there anyway to know if the autoloader succeeded when calling class_exists?

Was it helpful?

Solution 2

You have to check class_exists twice.

  1. To autoload if necessary
  2. To see if class now exists after autoload

My working code is:

$autoload = spl_autoload_functions() ? true : false; // spl_autoload_functions can return array, empty array or false, but we need boolean
$should_include = $autoload ? class_exists($className, true) : true;

if($should_include && !class_exists($className, false)){ // make sure the class does not exist before including
    if(is_readable($fileName)){
        include_once($fileName);
    } else {
        throw new Exception('Could not include ' . $className);
    }
}

This attempts to use previously-defined autoloaders before falling back.

OTHER TIPS

Just at the end of the autoloader check for class existence.

function __autoload($className) {

    //Your code here

    if(class_exists('You_Class', false)) {
        //succeed
    } else {
        //failure
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top