PHP namespacing and spl_autoload_register

谁都会走 提交于 2020-01-14 07:57:10

问题


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.

Directory strcuture:

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

Each class starts with:

namespace Foo;

Class ClassX {

Index.php:

<?php

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

$myObj = new Class1();

echo $myObj->doSomething();

This products an error Fatal error: Class 'Class1' not found in /var/www/myApp/index.php on line X

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

$myObj = new Foo\Class1();

However, then I get 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

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


回答1:


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();

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';
});



回答2:


Try to use DIR constant before your path, like:

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

It will ensure the relative path will always be the same.

You have to use the "correct" folder structure:

myproject/
-loader.php
-class/
-- Namespace1/
--- Class1.class.php
--- Class2.class.php

-- Namespace2/
--- Class3.class.php


来源:https://stackoverflow.com/questions/22494980/php-namespacing-and-spl-autoload-register

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