Include PHP Classes Auto-Magically

This has to be one of my favorite time savers.

If you’re an experienced PHP programmer you separate your common methods (aka: functions) into Class files.  Over time, this can become an organizational nightmare if your application became large.

There is an easy fix for this using PHP’s spl_autoload_register.  This not so well known function is called each time a Class is instantiated.  We can register our own functions to process the name of the Class being called, and easily include that Class in real-time.

Using this approach could not be any simpler.

Assuming you have included the SPL_AUTOLOADER scripts first, instantiating myClass() will auto-magically load the Class file myClass.php from the defined directory set in the myAutoloader() function.

It’s so simple you’ll ask yourself why you have not used this in the past.

Author: Richard Soares

I’m a freelance software developer with more than 20 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork.