Search code examples
phpautoload

PHP: Is AutoLoader able to load multiple class in a single php file?


Quote from Autoloading Classes :

Many developers writing object-oriented applications create one PHP source file per class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).

In PHP 5, this is no longer necessary. The spl_autoload_register() function registers any number of autoloaders, enabling for classes and interfaces to be automatically loaded if they are currently not defined. By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error.

Here comes the question, what if there are multiple classes in a single php file, is it suitable for autoload usage? or do I have to use require filepath statement?

For example, I have a protocol file under Protobuf\Client.php:

<?php

namespace Protobuf;
class A {
...
}
class B {
...
}

Solution

  • You would have to have some complex function to autoload those classes from the file named Client.php. The idea is to translate your namespace\classname into a directory\filename.php

    In this instance you would need to name your file A.php then when you call new Protobuf\A() it will find it. Otherwise you will have to create an overly-complex autoloader.

    Let's say you do create the autoloader so it finds the A class, then you can have B on the same file, but only if you have already autoloaded A otherwise you have to make some algorythm to know that A and B are on the same page.

    I would do the above pattern or the pattern adopted by apps like Magento that turn class names into directory paths by replacing underscores:

    $class = new Core_Classes_MyClass_Client();
    

    Your autoloader would replace the underscores and will load:

    Core/Classes/MyClass/Client.php //or similar scheme
    

    This to me is an easy way to do it, but I prefer using namespace and class. The above method is not in favor at the moment and from a naming standpoint, very easy to get mixed up since a lot of classes may be in the same folder or nested really deep into sub folders. You could get some really long naming for classes.