I am using classes with Wordpress and I am trying to autoload them in my functions.php file:
spl_autoload_register(function($class) {
include('classes/'.$class.'.php');
});
This is what my classes directory looks like:
- classes/
- project/
- Application.php
- Core.php
- Site.php
- Helpers.php
- utils/
- Helpers.php
- Twig.php
- views/
- Layout.php
- Modules.php
- pages/
- Home.php
- project/
Each class is namespaced based on the directory it is in. For example:
$homeClass = new \views\pages\Home();
When I autoload the classes, I get this error:
PHP Warning: include(classes/project\Application.php): failed to open stream: No such file or directory
Obviously the backslashes that are part of the namespacing don't work in the path. I could update my function to replace the backslashes with forward slashes like this:
spl_autoload_register(function($class) {
include('classes/'.str_replace("\\", "/", $class).'.php');
});
But it seems odd that that would be required. Am I missing something?
spl_autoload_register()is built-in to PHP and yet it requires an additional function (str_replace()) to accommodate namespaces. I would have assumed thatspl_autoload_register()would have been able to achieve this on it's own. - Michael Lynchspl_autoload_registerknows nothing about file paths at all. It doesn't even runincludefor you, it just gives you a fully-qualified class name, and it's up to you to do whatever you want to make that class come into existence. So it's not at all odd that you have to manipulate one string (the class name) to make it into another string (the path on disk according to your naming convention). - IMSoP