1
我想自动加载在我的班级使用命名空间,但我在index.php命名空间和自动加载错误,如何正确使用自动加载的PHP命名空间?
Error: Fatal error: Class 'foo\B' not found ...
例得到错误:
目录骨架:
\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;
}
}
而且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;
}
}
这个问题几乎是相同的,因为这一个:PHP autoload namespace但我包括其他文件夹中的index.php并不起作用。
如果我把相同的项目,但与下一个目录骨架,我没有得到任何错误。
\var\www
|_ foo
| |_ A.php
| |_ B.php
|
|_ index.php
的问题是:为什么如果我把在index.php文件夹中不起作用?
感谢