Undefined $class_name in autoloader using spl_autoloader_register() with WAMP?

Asked

Viewed 35 times

0

I’m trying to implement an autoloader for classes in my project, but I can’t make that code work... It returns the $class_name variable as Undefined.

function autoload_classes( $class_name ) {
   if ( ! empty( $class_name ) && file_exists( $class_name ) ) {
      include get_template_directory_uri() . '/core/classes/' . $class_name . '.php';
   } else {
      return false;
   }
}
spl_autoload_extensions( '.php' );
spl_autoload_register( 'autoload_classes' );

Could you help me? Thank you!

  • Could you translate the question?

  • Fuck!! Sorry I didn’t even notice kkkkk pera ae....

  • See help: http://devcia.com/criando-um-autoload-turbined/

1 answer

0

Here’s a autoload that I use:

function search_lib($lib, $file, $ds = '/'){
   // Verifica se o diretório informado é válido
   if (is_dir($lib)){

      // Verifica se o arquivo já existe neste primeiro diretório
      if (file_exists($lib.$ds.$file)) return $lib.$ds.$file;

      // Lista os subdiretórios e arquivos
      $dirs = array_diff(scandir($lib, 1), array('.','..'));
      foreach ($dirs as $dir) {

         // Verifica se é um arquivo se for, pula para o próximo
         if (!is_dir($lib.$ds.$dir)) continue;

         // Se for um diretório procura dentro dele
         $f = search_lib($lib.$ds.$dir, $file, $ds);

         // Caso não encontre retora false
         if ($f !== false) return $f;
      }

   }

   // Se o diretório informado não for válido ou se não tiver encontrado retorna false
   return false;
}
spl_autoload_register(
   function ($class){

      //if (strpos($class, '\\') !=- -1)
      //   $class = end( explode('\\', $class) );

      $libs = __DIR__.DS;
      $ext  = '.class.php';

      $file = search_lib($libs, $class.$ext);

      // Se encontrou inclui o arquivo
      if ($file !== false ) require_once $file;
      // Se não encontrar o arquivo lança um erro na tela. :)
      else {
         $msg = "Autoload fatal erro: Can't find the file {$class}{$ext} on {$libs}!";
         error_log($msg);
         exit('<br><br><strong>'.$msg.'</strong>');
      }

   }
);

It searches the class within the directory (and its subdirectories) in the variable $libs of the anonymity function in the spl_autoload_register. The extension of class files is configured in the variable $ext just below (I use .class.php, just change to your default).

Obs.: The code uses a constant DS which is an alias that I created for DIRECTORY_SEPARATOR, if you don’t use it so just change, or if you want to set it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.