I'm kinda confused on how Namespaces work with Autoload. I'm currently trying to learn PHP 7.4 and I came to the point where I wanted to learn how to use Namespaces and an Autoloader for the classes.
I'm working on Mac OS with MAMP.
This is the error message I am getting:
Warning: include_once(classes/Person/Person.class.php): failed to open stream: No such file or directory in /Applications/MAMP/htdocs/includes/autoloader.inc.php on line 4
My file structure is like this:
- classes
- Person
- Person.class.php
- includes
- autoloader.inc.php
- index.php
index.php:
<?php
include 'includes/autoloader.inc.php';
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<?php
$person = new \classes\Person\Person('Andre', 24, 'blue');
echo $person->getName();
?>
</body>
</html>
autoloader.inc.php:
<?php
spl_autoload_register(function($className) {
include_once str_replace("\\", "/", $className) . '.class.php';
});
Person.class.php
<?php
namespace classes\Person;
class Person {
private $name;
private $age;
private $eyeColor;
public function __construct($name, $age, $eyeColor) {
$this->name = $name;
$this->age = $age;
$this->eyeColor = $eyeColor;
}
}
I really don't understand why it is not working. I followed a lot of tutorials but nothing worked. Maybe it has something to do with a configuration in PHP?