This previous question shows how to force autoloading of all classes.
However I need to force autoloading of just one class on its own. How could I do that?
It mustn't:
- Involve changing the class's source code
- Rely on any part of the class's source code (methods, variables, modifiers e.g. it must be free to change from concrete to abstract without affecting this).
Also, preferably it would not involve coding the class's name as a string. (To help with IDE refactoring and so on).
The best option I have found so far would be to just use spl_autoload_call():
spl_autoload_call("Jodes\\MyClass");
or for non-namespaced classes:
spl_autoload_call("MyClass");
I had the same need recently. Doing
require_oncewas not an option because the class really needed to be located by the autoloader because of some more complex rules, there was no way to know exactly the path to the file with the class.Although the function
spl_autoload_call($classname)is designed to do precisely this, it suffers from a fundamental flaw: it will throw a FATAL ERROR in case you call it twice for the same classname or even if some of the child classes of that class were already loaded. This happens because it's not possible to redeclare classes in PHP:My solution for this problem is no rely on the side-effect of
class_exists($classname)which was not designed for this purpose, but is more configurable and, therefor, offers more control about triggering the autoloader.Even better, it has absolutely no problem on multiple calls or if something was already loaded in the inheritance chain. It simply has the side-effect (if you want) of requiring the file, if the class is not there yet!
With this you have a safe and idempotent way to load the class through the autoloader.
And, if you don't want to hard-code the string with the classname in there, from PHP version 5.5 onward, you can use the
::classpseudo constant, which is resolved at compile time to the string with the fully qualified classname (including namespaces):