1

I've a project like this:

project

Now i want to autoload all the php files in the folder classes and sub folders.

I can do that with this:

$dirs = array(
   CMS_ROOT.'/classes',
   CMS_ROOT.'/classes/layout',
   CMS_ROOT.'/classes/layout/pages'
);
foreach( $array as $dir) {
  foreach ( glob( $dir."/*.php" ) as $filename ) {
    require_once $filename;
  }
}

But i dont like this. For example.

"layout/pages/a.php" extends "layout/pages/b.php"

Now i get an error because a.php was loaded first. How do you people load your project files? Classes?

SOLVED :)

This is my code now:

spl_autoload_register('autoloader');
function autoloader($className) {
    $className = str_replace('cms_', '', $className);
    $className = str_replace('_', '/', $className);

    $file = CLASSES.'/'.$className.'.php';
    if( file_exists( $file ) ) {
    require_once $file;
    }
}
2

1 Answer 1

1

You should try this

<?php

spl_autoload_register('your_autoloader');

function your_autoloader($classname) {
    static $dirs = array(
      CMS_ROOT.'/classes',
      CMS_ROOT.'/classes/layout',
      CMS_ROOT.'/classes/layout/pages'
   );
   foreach ($dirs as $dir) {
      if (file_exists($dir . '/'. $classname. '.php')) {
          include_once $dir . '/' . $classname . '.php';
      }
   }
}

After registering your_autoloader with spl_autoload_register() it will be called by the php interpreter every time you access a class that:

  • Has not already been loaded with require_once() or include_once()

  • Is not part of the PHP internals

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That was a stupid question from me. I could figure it out for myself but had no time for that. Many thanks hek2mgl! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.