PHP Autoloading with SplClassLoader?

2019-03-18 12:40发布

问题:

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!