Question

I'm writing an application where all classes are using namespaces, and using spl_autoload_register() to load all classes dynamically.

Now I want to make use of a non-namespaced library (WideImage). As WideImage does not use namespaces, spl_autoload_register() does not work. So included the script manually:

    require( 'Library/WideImage/WideImage.php');
    $w = new WideImage();

But it still tries to autoload; and gives a fatal class not found error.

How can I override this autoload function?

By request:

spl_autoload_register(function( $class ) {

  $path       = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . CMS_PATH . DIRECTORY_SEPARATOR;
  $classFile  = str_replace( '\\', DIRECTORY_SEPARATOR, $class );
  $classPI    = pathinfo( $classFile );
  $classPath  = $path . $classPI[ 'dirname' ] ;

  $file = $classPath . DIRECTORY_SEPARATOR . $classPI[ 'filename' ] . '.class.php';

  if (file_exists($file)) {
require_once( $file );
  }

});

Edit: solution:

Change

if (file_exists($file)
to 
if (file_exists($file) && !class_exists($class)) {
Was it helpful?

Solution

Try to use class_exists() before loading.

OTHER TIPS

You can register multiple autoloaders with spl_autoload_register. This way you can write autoloaders for your own calsses and libraries. They trigger after each other and should return true or false - if the loaded souccessfully or not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top