Search code examples
phpoopspl

Use non-namespaced library in php


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

Solution

  • Try to use class_exists() before loading.