PHP名称空间和spl_autoload_register [英] PHP namespacing and spl_autoload_register

查看:95
本文介绍了PHP名称空间和spl_autoload_register的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我让spl_autoload_register正常工作,但后来我决定添加一些命名空间以实现PSR2遵从性,并且似乎无法使其正常工作.

I had spl_autoload_register working fine but then I decided to add some namespacing to bring in PSR2 compliance and can't seem to get it working.

目录结构:

-index.php
-classes/
  -Class1.class.php
  -Class2.class.php
  -Class3.class.php

每个班级始于:

namespace Foo;

Class ClassX {

Index.php:

Index.php:

<?php

spl_autoload_register(function($class) {
    include 'classes/' . $class . '.class.php';
});

$myObj = new Class1();

echo $myObj->doSomething();

这会产生错误Fatal error: Class 'Class1' not found in /var/www/myApp/index.php on line X

我的第一个想法是我需要在实例化中使用命名空间,因此我将index.php更改为:

My first thought was that I need to use a namespace with my instantiation, so I changed index.php to:

$myObj = new Foo\Class1();

但是,我得到了 Warning: include(classes/Foo\Class1.class.php): failed to open stream: No such file or directory in /var/www/myApp/index.php on line 6

如果我做手册,包括一切正常,include 'classes/Class1.class.php';,依此类推.

If I do manual includes everything works fine,include 'classes/Class1.class.php'; and so on.

推荐答案

所以问题在于,返回到spl_autoload_register$class是名称空间\类名, with 完整保留了反斜杠.因此,当我实例化一个新对象时:

So the problem was that the $class being returned to spl_autoload_register was the namespace\class name, with the backslash intact. So when I instantiated a new object:

$myObj = new Foo\Class1();

包含路径变为/var/www/myApp/classes/Foo\Class1.php,反斜杠破坏了路径.

The include path became /var/www/myApp/classes/Foo\Class1.php, the backslash breaking the path.

我实现了此功能以解决反斜杠的问题,尽管我不知道为什么这样做是必要的,但现在可以了.

I implemented this to fix the backslash, and it now works, although I do not know why this is necessary.

spl_autoload_register(function($class) {
    include 'classes/' . str_replace('\\', '/', $class) . '.class.php';
});

这篇关于PHP名称空间和spl_autoload_register的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆