I've been working on my framework over the weekend and drafting a concept for a mini application that I will do in my free time (if I finish the concept and like it). The concept has to do with two previous posts; essentially I am fufilling a promise in one of those two posts! But otherwise...
PHP's __autoload function is a great little helper function if you're coding in an object-oriented environment. It automates those dreadful PHP4 autoload-like functions by removing the use of calling a function to make sure a class is loaded/exists. Unfortunately __autoload lacks scope/namespace. What do I mean?
If we are working on a script and we are using third party code and both code bases define an __autoload function then we will encounter a serious problem! The options: either go into their code and recode it, remove their autoloader (not a viable option, they could be dependent on it), or write our own custom handler and do everything the PHP4 way. Guess what the best option is? Surprisingly enough, it's both the first and last one together.
Here's the solution: rename their __autoload function to anything else, create your own custom autoload function that would act as if it were the __autoload function, and then add both to the default autload stack.
function my_autoload($class_name = '') {
// moo
}
spl_autoload_register('my_autoload');
That was simple. The spl_autoload functions are only supported in PHP versions greater than or equal to 5.1.2. This means that if you are using an earlier version, you can easily replicate these functions by creating an __autoload() function which taps into a singleton stack that your custom spl_autoload functions modify.
Hope this makes people more aware of the realities of using others code and taking advantage of some of the more apparent than real panaceas that PHP offers.
A quick note to anyone who didn't realize this, but if the second parameter of class_exists is not set to FALSE, then __autoload will be called if it's defined.
- PHP by Peter Goodman on Jun 17, 2007 @ 10:56pm

