2014-10-11 57 views
-2

我有一个文件夹结构,如:自动加载的子文件夹

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{ 
    ... 
    } 

我想使用,在指数.php,myclass.php中的类。

但是,当我调用类的,我有这样的错误:

LogicException:类1级\ Level2的\ MyClass的不能被加载

看来它会尝试加载1级\ level2的\ MyClass的。 PHP的,但我已经在1级,所以应该只加载level2的\ myclass.php(否则的完整路径是根\ 1级\ 1级\ level2的\ myclass.php

我在哪里做错了吗?

+0

那么,首先,'class'是一个保留关键字。当你做'class Class'时 - php会恨你,class Class(){}'也不是你如何在php中定义类,你不需要'()'。首先验证示例中的代码并使用有效的代码更新问题。 – 2014-10-12 00:53:20

+0

对不起,它只是一个占位符名称,我简化了脚本... – 2014-10-12 09:16:27

回答

0

该iss ue是'自动加载器'不'知道'你的'根'目录。

的“默认” spl_autoload作品是追加“小写”的命名空间,如directores,您指定并追加其作为目录在include-path目录的方式。

注意:它不使用'DOCUMENT_ROOT'。

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

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

我的'根'目录是'testmysql'

在 '1级\(第二级)' 的 '类' 文件​​:

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

输出示例:PHP 5.3 .18在窗口xp上。

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 
+0

谢谢你的完整答案,我会尝试 – 2014-10-12 16:31:14

+0

完美,所以我只需要添加下面这行:'ini_set('include_path ',ini_get('include_path')。';'。$ _SERVER ['DOCUMENT_ROOT']。';');' – 2014-10-12 16:34:56