I want to autoload to use namespace in my classes but i get a error in the index.php
Error: Fatal error: Class 'foo\B' not found ...
Example:
directories skeleton:
\var\www
|_ foo
| |_ A.php
| |_ B.php
|
|_ view
| |_ index.php
A.php
<?php
namespace foo;
class A {
private $a;
public function __construct($a) {
$this->a = $a;
}
}
B.php
<?php
namespace foo;
use foo\A;
class B extends A {
private $b;
public function __construct($a, $b) {
parent::__construct($a);
$this->b = $b;
}
}
And Index.php
<?php
use foo\B;
define('ROOT', __DIR__ . DIRECTORY_SEPARATOR);
$b = new B('s', 2);
function __autoload($classname) {
$namespace = substr($classname, 0, strrpos($classname, '\\'));
$namespace = str_replace('\\', DIRECTORY_SEPARATOR, $classname);
$classPath = ROOT . str_replace('\\', '/', $namespace) . '.php';
if(is_readable($classPath)) {
require_once $classPath;
}
}
This question is almost the same as this one: PHP autoload namespace but I include the index.php in other Folder and does not work.
If I put the same project but with the next directories skeleton, I don't get any error.
\var\www
|_ foo
| |_ A.php
| |_ B.php
|
|_ index.php
The question is: Why if I put the index.php in a folder does not work?
Thanks