PHP5 reared it’s head mid 2004, 5 long years ago and all PHP developers rejoiced. Especially me. It gave us lots of new shiny tools to play with, including the obvious improved OO support and my particular favourite: the __autoload function.
For all you Java developers out there you know that you never have to include or require files, the Java language instinctively knows where to find them thanks to the compiler. So with the release of PHP5 I was thrilled to be able to do this—including every file you need is a real pain and takes precious time when developing.
There will be people out there saying that you shouldn’t use __autoload as it makes your application run slower. However, as computers have become so fast now, in my opinion, this becomes a moot point. Everything is all about maintainability, nowadays. If it saves me 5 hours in development time and 20 hours a year maintenance time I’m a happy man. I would also like to point out that includes_once is far, far more expensive than a simple include, which is what you people who do not use __autoload will have to do at some point. So the performance evens out.
I digress. This is supposed to be a quick guide, so let’s take our shoes and socks off and dive right in.
So what is this __autoload I speak of? Whenever you try and call a class that does not exist the function is triggered, giving you an opportunity to find the class, include it, and then tries to perform the class call for the second time. The perfect place for the __autoload is in your generic header file, so before any class has been called. So your header might look something like:
The __autoload file simply contains 1 function. No classes, just 1 function.
So now we somehow need to dynamically include our class whenver this function is called. The generally accepted way is to name your class with reference to its location in the file structure. So let’s assume we have all our PHP classes in the library folder split into 3 further folders called Model, Controller and View. If we had a formatting class that we wanted to place in the Model directory, then we would name the class Model_Format.
When we try and instantiate this class, new Model_Format(), it will trigger the __autoload function which will be passed 1 parameter, the $className variable which in this case is Model_Format. So we now need to try and find out where the file is and include it before the script dies on us. We can easily do this by changing the underscore to a forward slash which gives us the class location. So our __autoload will look like:
And there we have it, no need to ever include a class file again! You can of course extend the function to use some form of error checking or exception handing, in fact it is strongly recommended. Hope that saves you many an hour whilst debugging.