使用 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 frameworkhttp;
class Request
{
public function __construct()
{
echo __CLASS__ . " constructer!";
}
}
这是response.php
:
namespace frameworkhttp;
class Request
{
public function __construct()
{
echo __CLASS__ . " constructed!";
}
}
在 index.php
中我有:
require_once("SplClassLoader.php");
$loader = new SplClassLoader('frameworkhttp', 'system/framework');
$loader->register();
$r = new Request();
我收到此错误消息:
Fatal error: Class 'Request' not found in C:wampapachehtdocsphp_autoloadingindex.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 frameworkhttpRequest;
$r = new Request();
?>
希望这有帮助!
这篇关于使用 SplClassLoader 自动加载 PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!