12

我正在学习 PHP 5.3 中的命名空间,我想使用命名空间自动加载。我找到了这个SplClassLoader 类,但我不知道它是如何工作的。

假设我有这样的目录结构:

system
  - framework
    - http
      - request.php
      - response.php
index.php
SplClassLoader.php

如何启用类自动加载?应该request.phpresponse.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在我的项目中使用它以加载/需要我的类,以及我应该如何设置和命名文件夹和命名空间?

4

1 回答 1

11

您的文件和目录名称需要与您的类和命名空间的大小写完全匹配,如下例所示:

system
  - framework
    - http
      - Request.php
      - Response.php
index.php
SplClassLoader.php

另外,注册SplClassLoader对象时只需要声明根命名空间,如下:

<?php

    require_once("SplClassLoader.php");
    $loader = new SplClassLoader('framework', 'system/framework');
    $loader->register();

    use framework\http\Request;

    $r = new Request();

?>

希望这可以帮助!

于 2012-05-24T04:02:04.473 回答