Over a million developers have joined DZone.

PHP - Stop including class files and use __autoload() instead

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

PHP added several magic methods in PHP5.  __autoload(), however, isn’t one of them.  But that doesn’t make it any less useful.  In fact it’s one of the gems in PHP that I find to be relatively under used.  It’s common for PHP applications to break out classes into their own files.  This becomes cumbersome when working on large projects as you wind up with numerous include/require calls for any given page.  There’s got to be a better way...

Consistency is your friend
I’m sure you name your class files consistently so you can probably skip this section.  Apparently, since you’re reading this, you do not have any rhyme or reason for your class file names.  It doesn’t really matter what it is as long as it’s consistent and predictable.  For example, EpiCode contains a models directory which contains all of the PHP class files.  The file names follow the pattern ClassName.php.  I know that class A is defined in models/A.php.

What can __autoload() do for you?
Did you know that PHP will call __autoload() if you try to call a function which is not yet defined?  You simply have to define it and let it know where to find the class file.  Let’s use my example of placing all class definitions inside a models directory with the filename being the same as the class name.  Your __autoload() function may look something like this.

function __autoload($className)
require_once "./models/{$className}.php";

// Instantiate class A without including it and __autoload() will do so on your behalf
$ClassA = new A();

Make your code less ugly
If you can’t spare an extra function call here or there then __autoload() may not be for you. Though I would begin to question your reasoning. The upside is that your code could become significantly cleaner and more maintainable. The upside of easy to read code often trumps everything else.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}