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.