spl_autoload_register在错误的目录/文件中搜索

时间:2013-11-05 11:39:03

标签: php spl-autoload-register

我已将以下代码放在我的函数文件(MyFunctions.php)中:

spl_autoload_register               
( 
    function( $Class )              
    { 
        $Class = str_replace ( "..", "", $Class );
        include $_SERVER['DOCUMENT_ROOT'] . '/phpsb/class library/' . $Class . '.php';
    }
);

但是当我从脚本中引用类/对象时,spl_autoload_register会在定义它的函数文件中搜索,而不是类库目录:

Warning: include(C:/xampp/htdocs/phpsb/class library/FormClass.php): failed to open stream: No such file or directory in C:\xampp\htdocs\sandbox\function library\MyFunctions.php 

1 个答案:

答案 0 :(得分:0)

试试这个:

spl_autoload_register(function ($className) {
    $className = (string) str_replace('\\', DIRECTORY_SEPARATOR, $className);
        include_once(dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . $className . '.php');
});

此代码支持名称空间,我假设MyFunctions.php位于您的dinamically加载的PHP文件的同一目录中。