0

In a custom WordPress plugin I have a folder /classes with about 20 classes. Classes sometimes change, come and go. I want all those classes from the folder to be loaded automatically.

No my idea was to load those files by a simple loop require:

foreach (scandir(dirname(__FILE__)."/classes/") as $filename) {
    $path = dirname(__FILE__) . '/' . $filename;
    if (is_file($path)) {
        require $path;
    }
}

However this does not work because there are subclasses loaded before superclasses and I get a fatal error.

PHP usually solves this problem with the spl_autoload_register() function.

However this seems not to work if used in multiple plugins. Has anybody found a good solution to this problem yet?

2
  • Have you considered using the composer autoloader? I have multiple plugins each with their own composer generated autoloaders, and they work just fine
    – Tom J Nowell
    Nov 14 '18 at 17:42
  • Not yet thats a good idea.
    – Blackbam
    Nov 14 '18 at 17:56
0

Composer Autoloader as suggested in the comments is the best way to do it. Just use composers classmap feature:

"autoload": {
    "classmap": ["classes/"]
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.