用SplClassLoader自动加载PHP? [英] PHP Autoloading with SplClassLoader?
问题描述
我正在学习PHP 5.3中的名称空间,我想使用名称空间自动加载.我找到了 SplClassLoader类,但是我不知道它是如何工作的.
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
如何启用课程自动加载功能? request.php
和response.php
应该具有哪些命名空间?
How do I enable class autoloading? What namespaces should request.php
and response.php
have?
这是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
,以便它加载/需要我的类,以及如何设置和命名文件夹及名称空间?
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?
推荐答案
您的文件名和目录名必须与您的类和名称空间的大小写完全匹配,如以下示例所示:
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
此外,您只需要在注册SplClassLoader对象时声明根名称空间,如下所示:
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();
?>
希望这会有所帮助!
这篇关于用SplClassLoader自动加载PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!