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文件夾中不起作用?
感謝