Question

From php.net:

In PHP 5, this is no longer necessary. You may define an __autoload() function which is automatically called in case you are trying to use a class/interface which hasn't been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.

Now I am wanting to know, is it bad practice to solely use __autoload to load the appropriate classes on a dynamic site?

The way my site is setup is to include files into the index.php file, for example http://www.site.com/index.php?p=PAGE-I-WANT-TO-LOAD

So if I am on the forums section or the blogs section of my site, I want only appropriate classes and functions to be loaded, so I use autoload but I never include a file manually, should I be using __autoload as a last resort or is what I am doing fine even on a high traffic system?

Was it helpful?

Solution

Bad? No. __autoload() is one of my favorite additions to PHP 5. It removes the responsibility (and annoyance) of manually having to include/require the class files necessary to your application. That being said, it's up to you as the developer to ensure that only the 'appropriate classes' are loaded. This is easily done with a structured naming scheme and directory structure. There are plenty examples online of how to properly use __autoload(), do a Google search and you'll find plenty of information.

OTHER TIPS

Autoload is a good way to load only what classes is needed.

In PHP 5 >= 5.1.2, most of the problems with the old __autoload() dissapeared, thanks to spl_autoload_register().

Now I am wanting to know, is it bad practice to solely use __autoload to load the appropriate classes on a dynamic site?

Not at all. You can rely on autoload, all you need to do is to devise a good naming convention and implement an efficient autoloader.

There is one major issue to consider. Autoloading and Zend Guard do not play well together, because Zend Guard tends to rename things, which will mean that the naming convention you decided to use will most likely not be the same. If you will be using Zend Guard (or any other obfuscator for that matter) you will most likely be forced to include all the files by hand.

Here is a quote from the Zend Guard user guide:

Autoloading classes will not work since the filename on the disk would not match the obfuscated class name.

The only danger to __autoload() is if you define a poor autoloading function. Generally, all you're going to get in terms of a performance hit is a few disk seeks as PHP looks for the right files that contain your classes. The upside is getting rid of all those annoying include() calls.

If you're worried about performance at this level, then you should already be using an opcode cache such as APC.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top