PHP autoloader issues

By | February 10, 2011

Since PHP 5.x we are encouraged to develop in a more object oriented way. This is why they developed class support for us ;-). Now to make our web applications even more modular you might consider putting each class in a seperate PHP file, just like Java and C++ developers have been doing for years now. But here is where it becomes tricky, how does PHP know which files to load automatically.

Of course you could include every single file that you might need manually at the top of your index.php. But what if you don't need every single class every time a page is loaded, do you really want to create that kind of an overhead in loading un-needed files? I didn't, so I started looking into the autoloader functionality of PHP. What this feature does is allow you to scan through files in the predefined include directories and attempts to locate the class.

So what I did was build a simple autoloader function to scan each file in predefined directories to find the classes, and if found to stop. To my surprise this was working rather well. All classes that where needed would automatically get loaded by my little autoloader function. However somehow one particular class was not able to be loaded for some reason. The setup was something simple, something like:

  • A predefined class A
  • A class B which extended class A
  • A class C which extended class B
  • A class D which extended class C, and was located in a separate directory as it was specific for the website

All of the classes loaded beautifully, except for class D. For some reason when I tried using it I got exceptions that class C was undefined. When I added some debugging to find out which files where loaded I did see every file for classes A, B and C being loaded, but the actual classes defined inside where not added to PHP. Somehow I have magically created a black whole in PHP that would include files and then forget to create the class definitions internally. To this day I still haven't figured out why PHP refused to store the actual classes in its memory.

The quick fix I applied was ugly and stupid, just manually load the classes and build a big if statement around them to prevent duplicate declarations using the class_exists function.

One thought on “PHP autoloader issues

  1. Zyx

    It should be worth pointing out that you should not invent your own class naming conventions and autoloading algorithms, because such projects are extremely hard to use somewhere else. We have a PSR-0 class naming proposal, and there is a couple of good, universal class loaders for them. All you have to do is to make use of them.

    Reply

Leave a Reply