Somewhere in the past i already covered autoloading on this blog but lately while developing my WordPress Job Board Plugin i decided to add an autoloader (there are over 30 libraries right now so it makes at least some sense), besides if we are given some cool tools why not to use them, right?
Either way, once i decided that i want to have an autoloader i realized that, that someone may already add an __autoload function, so i cannot risk redeclaring it. The only way around was to register auto loader with spl_autoload_register. That was a great idea … for a while because it turns out that once you register auto loader with spl_autoload_register, __autoload is unregitered.
I could do a nice little hack and write
spl_autoload_register("__autoload");
but that wouldn’t do a trick either, because if my plugin would be loaded before plugin that is declaring __autoload function, it would cause fatal error on first try to automatically load a library.
So i went further and created this code, that solves all the problems i described in previous paragraphs – and it’s just few lines of code.
function my_autoloader($class) { // do some autoloading here } function autoload_proxy($class) { if(function_exists("__autoload")) { __autoload($class); } } spl_autoload_register("my_autoloader"); spl_autoload_register("autoload_proxy");
So the solution is to simply register two spl auto loaders, one being an autoloader you want to use to load your libraries while the other would be calling an __autoload function if someone would register it, if not then it would do nothing. It’s a fool proof solution to autoloading objects in your WordPress plugins for example.



3 Comments on "PHP plugin autoload"
Interesting.
Do you have to register your autoloader in every php class file or just in your centralized dispatcher?
Autoloader (in my opinion) should be registered only once usually in main plugin file before any library is loaded.
Doesnt work