PHP Autoloading with SplClassLoader?

我们两清 提交于 2019-12-04 10:29:46

问题


I'm learning about namespaces in PHP 5.3 and I would like to use Namespaces Autoloading. I found this SplClassLoader class, but I can't figure out how it works.

Let's say I have directory structure like this:

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

How do I enable class autoloading? What namespaces should request.php and response.php have?

This is the request.php:

namespace framework\http;

class Request
{
    public function __construct()
    {
        echo __CLASS__ . " constructer!";
    }
} 

And this is the response.php:

namespace framework\http;

class Request
{            
    public function __construct()
    {      
        echo __CLASS__ . " constructed!";                
    }           
}   

And in index.php I have:

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

$r = new Request();

I get this error message:

Fatal error: Class 'Request' not found in C:\wamp\apache\htdocs\php_autoloading\index.php on line 8

Why is this not working? How can I use SplClassLoader in my projects so it loads/requires my classes, and how should I setup and name folders and namespaces?


回答1:


Your file and directory names need to match the case of your classes and namespaces exactly, as in the following example:

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

Additionally, you only need to declare the root namespace when registering the SplClassLoader object, as follows:

<?php

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

    use framework\http\Request;

    $r = new Request();

?>

Hope this helps!



来源:https://stackoverflow.com/questions/9423366/php-autoloading-with-splclassloader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!