tags:

views:

200

answers:

2

I'm an author of a growing library of PHP + QuickBooks related code. I'd like to utilize PHPs __autoload() function, however my code is a library that other people can include() into their own applications, so I can't rely on __autoload() being not already defined.

Is there a way to have multiple __autoload() functions?

I saw spl_autoload_register() in the PHP manual, but not all of my users have the SPL extension installed, so I can't rely on that. If there was a way to fall-back to using this and use normal require/include statements by default, I might consider that.

Does anyone else have any other clever solutions to this issue? It seems like a glaring oversight to only be able to have a single __autoload() function...

+2  A: 

I saw spl_autoload_register() in the PHP manual, but not all of my users have the SPL extension installed, so I can't rely on that.

Ignore them, it's compiled in by default and can't even be disabled in 5.3.0. Don't sacrifice your framework to please the minority.

The Pixel Developer
This is not an option, and not an answer. Probably 50% of my users don't have SPL enabled, and don't have the ability to upgrade PHP by themselves (shared hosting). Compatibility is paramount of class libraries, especially ones that get me paid.
Keith Palmer
Direct them to a hosting provider with some common sense. I'd love hear their reasons for disabling SPL. Better yet, complain to the hosting provider and ask for it.
The Pixel Developer
Believe me, I have already complained and gotten next to no helpful response. Some of these people have applications installed which use class names that SPL conflicts with, some of them have stupid hosting providers, some of the hosting providers are just too lazy to do the upgrade, etc. etc. etc. If I had my way, everyone would be on 5.3.0 and I wouldn't have to worry about this. However, it's not a decision I can force them to make without losing piles of money and upsetting a lot of people. Soooo... I need a solution that doesn't depend on SPL.
Keith Palmer
+1  A: 

I have decided that the way to go about this and also preserve backward compatibility is to write my own "Loader" class.

Instead of using require_once 'TheFile.php', I now use Loader::load('TheFile.php');. The Loader::load() method does the following:

if ( the function spl_autoload_register exists )
   register an autoloader
   return true
else 
   check if the file has already been included (static array var with a list of files)
   if not included yet
      require $file
   return true

This gives me the flexibility to use the autoloader if their PHP installation supports it, and otherwise fall back to just doing normal require $file; type stuff.

Keith Palmer