我正在学习 PHP 5.3 中的命名空间,我想使用命名空间自动加载。我找到了这个SplClassLoader 类,但我不知道它是如何工作的。
假设我有这样的目录结构:
system
- framework
- http
- request.php
- response.php
index.php
SplClassLoader.php
如何启用类自动加载?应该request.php
和response.php
有哪些命名空间?
这是request.php
:
namespace framework\http;
class Request
{
public function __construct()
{
echo __CLASS__ . " constructer!";
}
}
这是response.php
:
namespace framework\http;
class Request
{
public function __construct()
{
echo __CLASS__ . " constructed!";
}
}
在index.php
我有:
require_once("SplClassLoader.php");
$loader = new SplClassLoader('framework\http', 'system/framework');
$loader->register();
$r = new Request();
我收到此错误消息:
Fatal error: Class 'Request' not found in C:\wamp\apache\htdocs\php_autoloading\index.php on line 8
为什么这不起作用?我如何SplClassLoader
在我的项目中使用它以加载/需要我的类,以及我应该如何设置和命名文件夹和命名空间?