0

I'm trying to autoload classes in PHP that are stored in subfolders within the classes folder. Here is the directory and file structure:

htdocs
  SANDBOX
  index.php
  classes
    app
      app1.php
    utlity
      utility1.php

Here are the contents of index.php:

<!DOCTYPE HTML>
<html>
<?php

//autoload classes
# first attempt
spl_autoload_register(function($class) {
    require_once 'classes/' . $class . '.php';
});

# second attempt
// spl_autoload_extensions(".php");
// spl_autoload_register();

//render stuff in browser
echo '<p>this is the test page</p><br>';
echo Utility1::greeting();
echo App1::greeting();
?>
</html>

Here are the contents of app1.php:

<?php
namespace classes/app;

class App1
{
    public static function greeting()
    {
        return 'app<br>';
    }
}
?>

Here are the contents of utility1.php:

<?php
namespace classes/utility;

class Utility1
{
    public static function greeting()
    {
        return 'utility<br>';
    }
}
?>

Neither attempt 1 nor attempt 2 in index.php have resulted in successful autoloading of the classes. What modifications need to be made to get the autoloading to work with this file structure? The ideal autoloading approach will allow additional subfolders to be added to the classes folder in the future and not require modification to the autoloading code.

knot22
  • 2,648
  • 5
  • 31
  • 51

1 Answers1

0

You classes are located in a namespace, you need to provide the proper namespace when accessing them in your code:

echo \classes\utility\Utility1::greeting();
echo \classes\app\App1::greeting();

Apart from that your autoloader basically looks fine. You should convert the parameter to lowercase (or name the file in the correct case) and replace \ with / however (for full operating system interoperability.

TimWolla
  • 31,849
  • 8
  • 63
  • 96