Autoload Classes w/ PHP


Are you using an object oriented approach with PHP and finding that your memory usage is going through the roof with the more classes that you add? PHP's autoload() function enables you to automatically load classes when they are used which will greatly reduce the overhead of your application.

In addition to the basics of autoloading classes there is also a primitive example of exception handling which will be enough to get you to the point of catching exceptions instead of dealing with errors.

Let's start by cloning or forking the repository which is available here:

PHP Autoload Repository

The autoload() function in this example (found in controller.php, line #2) looks for classes in ./Classes/ with the extension .class.php so any classes you add to this example must follow that pattern, see Social.class.php for reference. There is a method in the Social class (validateString()) which does two things: 1) verify that all parameters have a value (or in other words, !empty) and 2) verify that all parameters being passed are in fact of type string. If either of those tests fail an exception is thrown and our controller catches it. Try modifying line 9 and removing one of the parameters, or just comment out line 9 and uncomment out line 11. Doing either of those things will result in an exception being thrown which will help illustrate what is going on behind the scenes with the try/catch logic.

I hope this helps shed some light on the concept of autoloading classes and using exceptions. If you have questions please feel free to leave them in the comments!