在子文件夹中自动加载

时间:2014-10-11 23:48:08

标签: php

我有一个文件夹结构,如:

Root
+--Level1
|  +--index.php
|  |
|  \--Level2
|     +--myclass.php

的index.php:

namespace Level1;

spl_autoload_extensions('.php');
spl_autoload_register();

Level2\myClass::myMethod();

class.php:

namespace Level1\Level2;
    class myClass{
    ...
    }

我想在index.php中使用myclass.php中的类。

但是当我打电话给班级时,我有这个错误:

LogicException:无法加载类Level1 \ Level2 \ myClass

它似乎尝试加载level1 \ level2 \ myclass.php,但我已经在level1,所以它应该只加载level2 \ myclass.php(否则完整路径将是root \ level1 \ level1 \级别2 \ myclass.php

我在哪里做错了?

1 个答案:

答案 0 :(得分:0)

问题是“自动加载器”并不“知道”您的“Root”目录。

'default' spl_autoload 的工作方式是将您指定的'lowercase'命名空间作为directores追加,并将它们作为目录附加到 include-path

注意:它不使用'DOCUMENT_ROOT'。

要解决您遇到的问题,您必须在 PHP'include_path'中包含“Root”路径。

以下是一些将“Root”目录添加到“include_path”的代码。

我的'Root'目录是'testmysql'

'level1 \ level2'中的'class'文件:

namespace Level1\Level2;

class myClass {

    public static function staticLocation()
    {
        echo '----------  ', '<br />';
        echo 'method    : ', __METHOD__, '<br />';
        echo 'class     : ', __CLASS__, '<br />';
        echo 'namespace : ', __NAMESPACE__, '<br />';
        echo 'directory : ', __DIR__, '<br />';
        echo 'filepath  : ', __FILE__, '<br />';
    }
}

显示所有详细信息的 index.php

namespace Level1;

spl_autoload_extensions('.php');
spl_autoload_register();

echo '<br />Document Root: ', $_SERVER['DOCUMENT_ROOT'], '<br />';

// Define the root path to my application top level directory (testmysql)
define('APP_ROOT',  $_SERVER['DOCUMENT_ROOT'] .'/testmysql');

echo '<br />', 'My Application Root directory: ', APP_ROOT, '<br />';

echo '<br />', 'This File: ', __FILE__, '<br />';
echo '<br />', 'Current Directory : ', __DIR__, '<br />';

echo '<br />', 'Include path (before): ', ini_get('include_path'), '<br />';
ini_set('include_path', ini_get('include_path') .';'. APP_ROOT .';');
echo '<br />', 'Include path (after): ', ini_get('include_path'), '<br />';

Level2\myClass::staticLocation();

我的系统上的示例输出:窗口xp上的PHP 5.3.18。

P:/developer/xampp/htdocs

My Application Root directory: P:/developer/xampp/htdocs/testmysql

This File: P:\developer\xampp\htdocs\testmysql\level1\index.php

Current Directory : P:\developer\xampp\htdocs\testmysql\level1

Include path (before): .;P:\developer\xampp\php\PEAR

Include path (after): .;P:\developer\xampp\php\PEAR;P:/developer/xampp/htdocs/testmysql;
----------
method : Level1\Level2\myClass::staticLocation
class : Level1\Level2\myClass
namespace : Level1\Level2
directory : P:\developer\xampp\htdocs\testmysql\level1\level2
filepath : P:\developer\xampp\htdocs\testmysql\level1\level2\myClass.php