Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

· Web Dev Zone
Free Resource

Add user login and MFA to your next project in minutes. Create a free Okta developer account, drop in one of our SDKs to your application and get back to building.

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.

Launch your application faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}