PHP's __autoload() (documentation) is pretty interesting to me. Here's how it works:
- You try to use a class, like
new Toast_Mitten()(footnote1) - The class hasn't been loaded into memory. PHP pulls back its fist to sock you with an error.
- It pauses. "Wait," it says. "There's an
__autoload()function defined." It runs it. - In that function, you have somehow mapped the string
Toast_Mittentoclasses/toast_mitten.phpand told it to require that file. It does. - Now the class is in memory and your program keeps running.
Memory benefit: you only load the classes you need. Terseness benefit: you can stop including so many files everywhere and just include your autoloader.
Things get particularly interesting if
1) Your __autoload() has an automatic way of determining the file path and name from the class name. For instance, maybe all your classes are in classes/ and Toast_Mitten will be in classes/toast_mitten.php. Or maybe you name classes like Animal_Mammal_Weasel, which will be in classes/animal/mammal/animal_mammal_weasel.php.
2) You use a factory method to get instances of your class.
$Mitten = Mitten::factory('toast');
The Mitten::factory method can say to itself, "let's see, do I have a subclass called Toast_Mitten()? If so, I'll return that; if not, I'll just return a generic instance of myself - a standard mitten. Oh, look! __autoload() tells me there is a special class for toast. OK, here's an instance!"
Therefore, you can start out using a generic mitten throughout your code, and when the