Dino Cajic Dino Cajic - 4 years ago 143
PHP Question

Dynamic path to spl_autoload

Currently I'm recursively looking through my classes folder in order to find the path to my class in order to include it. The problem is, I have many different classes in various different folders that I would like to include. The code that I've created is messy but it works.

The code below is not the recursive function that I've created but it will work for a defined path within the myAutoloader() function.

Is there any way to pass a path to spl_autoload function in PHP?


function myAutoloader($className) {
$path = '/classes';

include $path . $className . '.php';


// this one will work, as its path is specified in spl_autoload
$myClass1 = new MyClass1();

//this is located in /classes/other so it wont work
$myClass2 = new MyClass2();

Answer Source

There is no way to pass the path to the callback function specified in spl_autoload_register.
You can only create this awareness inside the function:

function myAutoloader($className) {

    $paths = array(
    'Class1' => '/subpath',
    'Class2' => '/subpath/extra',

    include $paths[$className] . '/'. $className . '.php';

That said, I strongly discourage you folliwing this approach. Instead I really suggest you to:

  • Let composer create your autoload insted doing this manually.
  • Invest 10 minutes reading PSR-4 Specifications.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download