我想自动加载以在我的类中使用命名空间,但在 index.php 中出现错误
Error: Fatal error: Class 'foo\B' not found ...
例子:
目录骨架:
\var\www
|_ foo
| |_ A.php
| |_ B.php
|
|_ view
| |_ index.php
一个.php
<?php
namespace foo;
class A {
private $a;
public function __construct($a) {
$this->a = $a;
}
}
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 放在一个文件夹中不起作用?
谢谢
最佳答案
那是因为 ROOT 常量指向 /var/www/view/
,不是 /var/www/
.当您将 index.php 移动到不同的目录时,它会发生变化。
你可能想看看函数 set_include_path()
.有了它,您可以设置多个根目录定义。然后,您可以完全取消 ROOT 常量。
关于php - 命名空间和自动加载错误,如何正确使用带自动加载的 PHP 命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22969630/