0

I have a custom autoloader in php. The search pathes are set in an array. The loading itself:

  • $classname the name of the nonloaded class
  • $path the directories
  • $autoloadClassPaths [classname] => absolute filename

THIS IS a spl_autoload_register() registered function!

    if (!isset($autoloadClassPaths[$classname]))
    {
        foreach ($path as $dir)
        {
            foreach (new DirectoryIterator($dir) as $fileinfo)
            {
                if (substr($fileinfo->getFilename(), -4) == '.php')
                {
                    $tokens = token_get_all(file_get_contents($fileinfo->getPathname()));
                    $count = count($tokens);
                    for ($i = 2; $i < $count; $i++)
                    {
                          if (  ($tokens[$i - 2][0] == T_CLASS || $tokens[$i - 2][0] == T_INTERFACE)
                             && $tokens[$i - 1][0] == T_WHITESPACE
                             && $tokens[$i][0] == T_STRING)
                          {
                               $autoloadClassPaths[$tokens[$i][1]] = $fileinfo->getPathname();
                          }
                    }
                }
            }
        }
    }
    else
    {
        require ($autoloadClassPaths[$classname]);
    }

the problem is now I met with namespaces. How to write this autoloaded?

John Smith
  • 283
  • 5
  • 12

1 Answers1

1

with an autoloader such as this, you get the classname of any class like SomeClassName. in case of a namespaced class you get the namespace with the classname like this SomeNamespace\SomeClassName. it includes all information you need to load the file if you have a clean directory structure. (like: library\SomeNamespace\SomeClassName.php).

Andreas Linden
  • 12,489
  • 7
  • 51
  • 67