spl_autoload_register在包含的文件中不起作用


spl_autoload_register not working in included files

我使用spl_autoload_register来加载类。

我有一个包含init.php文件的index.php文件。spl_autoload_register函数在init.php文件中调用。

index.php文件中,它工作正常:我可以创建类和东西,它们的名称被解析。

但稍后,在index.php中,我将包含另一个文件work.php来执行一些特定任务。

奇怪的是,在work.php中,找不到我正在使用的类。

如果我在work.php中再次调用spl_autoload_register,则可以解析该类。

真正奇怪的是,这种行为并不一致:在我的测试服务器上,我不必复制spl_autoload_register调用,但在我的生产服务器上,这是强制性的。

我是否遗漏了php.ini中的一些选项?

编辑/更新:这是init.php文件上的内容,以防万一:

<?php
function my_autoload($class){
    include 'class/' . $class . '.class.php';
}
spl_autoload_register('my_autoload');
?>

还有我的index.php:

<?php
require_once 'include/init.php';
$barcode = new Barcode();
// here is a bunch of test and stuff
include 'work.php';
?>

还有我的作品。hp:

<?php
$myObj = new Barcode();
// more useles stuff
?>

条形码在index.php代码部分创建得很完美,但在work.php部分失败了。。。

实际上,我是个笨蛋。问题不在于include-path等,而在于apache配置:MultiViews。

我的网站只有一个访问点:index.php。我使用url重写来重定向上面的所有内容。但多亏了多视图选项,如果url与文件同名,则url重写无法正常工作。

我的目录包含index.php和work.php。

我的重写脚本是这样的:如果你点击www.mywebsite.com/work,你就会进入index.php,param url=work。index.php初始化所有内容,然后包括work.php

但多亏了MultiViews选项,如果我访问www.mywebsite.com/work,它会搜索文件,找到work.php,然后直接调用它。含义:无init,含义:无spl_autoload_register。

谢谢你的回答,很抱歉。

检查include_path设置是否包含本地目录。

一般来说,使用相对路径不是一个好主意。很容易创建一个相对于init.php文件的绝对路径,如下所示:

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

此代码假定init.php文件与"class"文件夹位于同一文件夹中。

此外,不要盲目地包含给定路径中可能存在或不存在的文件,而是在包含文件之前检查文件的存在:

function my_autoload($class){
    $file = __DIR__.'/class/' . $class . '.class.php';
    if(file_exists($file)) {
       include $file;
    }
}

请注意,__DIR__是一个PHP 5.3功能,在带有PHP 5.2的主机上不可用。你可以用dirname(__FILE__) 代替它

此外,请注意,在Linux上,该文件是以区分大小写的方式搜索的,在大多数Mac OS X安装中,该文件都是不区分大小写的。如果实例化类MyClass,Linux将查找MyClass.class.php,而Mac OS X也会加载该类(如果它在名为myclass.class.phpMyclass.class.php等的文件中(。