phpautoloaderspl-autoloader

Error when using SplClassLoader


First off, I'm trying my hand using the following SplClassLoader -https://gist.github.com/221634

Here is my file structure:

/root/f1/f2/APS/Common/Group.php
/root/f1/f2/index.php
/root/f1/f2/SplClassLoader.php

Here is my test class called Group (Group.php)

namespace APS\Common;

class Group{
...
}

Here is the index.php file that is calling everything:

require "SplClassLoader.php";
$classLoader = new SplClassLoader('APS', 'APS/Common');
$classLoader->register();

I'm getting the following error:

Fatal error: Class 'Group' not found in /root/f1/f2/index.php on line 17

I've tried every conceivable combination when passing the namespace and path to the loader. It never works.

Update #1 - Line 17 in index.php:

16: use APS\Common;
17: $x = new Group();

Update #2 - Configuration info

Update #3 - I'm getting a different error message now.

The code in place:

require "SplClassLoader.php";
$classLoader = new SplClassLoader('APS', '/root/f1/f2');
$classLoader->register();

use APS\Common;
$x = new Common\Group();

Error message that I'm getting:

Warning: require(/f1/f2/APS/Common/Group.php): failed to open stream: No such file or directory in /root/f1/f2/SplClassLoader.php on line 133 

Solution

  • In my case, here is the solution that seems to work.

    require "SplClassLoader.php";
    $classLoader = new SplClassLoader('APS\Common', __DIR__);
    $classLoader->register();
    
    use APS\Common;
    $x = new Common\Group();
    

    I had to use the magic constant DIR for it to work. The second parameter seems to need to point to the physical path of the root of where the classes reside. Then, the namespace gets added to locate them in the file system.