加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 来自不同文件和目录的自动加载类和函数

发布时间:2020-12-13 13:33:25 所属栏目:PHP教程 来源:网络整理
导读:我有这个自动加载代码: function __autoload($class_name){ //class directories $directorys = array( './Controls/','./Config/','./Utility/' ); //for each directory foreach($directorys as $directory) { //see if the file exsists if(file_exists(
我有这个自动加载代码:
function __autoload($class_name)
{
    //class directories
    $directorys = array(
        './Controls/','./Config/','./Utility/'
    );
    //for each directory
    foreach($directorys as $directory)
    {
        //see if the file exsists
        if(file_exists($directory.$class_name . '.php'))
        {
            require_once($directory.$class_name . '.php');
            //only require the class once,so quit after to save effort (if you got more,then name them something else
            return;
        }
    }
}

我有三个目录,他们持有我所有的类和函数.

我可以在Controls目录中创建一个自动加载文件,并使用它来加载其他php文件中的所有函数或类,我的意思是例如/portal/main/index.php中的index.php文件

是否可以加载index.php文件中的控件和配置类,而不包括index.php文件上面的任何文件

我的意思是自动加载会自动了解哪个文件正在请求类或函数,并为其包含该文件.

更新的代码:

function __autoload($class_name)
{
    //class directories
    $directorys = array(
        '/Controls/','/Config/','/Utility/'
    );
    //for each directory

    $ds = "/"; //Directory Seperator
    $dir = dirname(__DIR__); //Get Current file path
    $windir = ""; //Windows Directory Seperator
    $path = str_replace($windir,$ds,$dir);

    foreach($directorys as $directory)
    {
        //see if the file exsists
        if(file_exists( $path . $directory . $class_name . '.php'))
        {
            require_once( $path . $directory . $class_name . '.php');
            //only require the class once,then name them something else
            return;
        }
    }
}

我已经更新了代码并且它包含了文件,但我唯一的问题是这个函数没有自动运行,

例如我的自动加载文件位于:root / Controls / autoload.php中
我需要一些类和函数:root / portal / index.php

当我在index.php中定义类时,我得到文件不存在的错误
我应该手动调用index.php中的autoload.php文件

我如何使自动加载智能,我不应该包括在每个文件中包括类?

请帮帮我.
提前致谢

简单的手动解决方案:将您的自动加载文件放在项目根目录中并将其包含在索引文件中,这将完成工作.

但如果你想使用htaccess或php.ini:
将名为.user.ini的文件放入文档根目录,并在其中添加auto_prepend_file指令:

auto_prepend_file = /home/user/domain.com/init.php

该文件必须位于PHP的include_path中.因此,您必须将文件的目录设置为php.ini中的include_path,或者使用php_value语句在.htaccess中执行.

php_value include_path ".:/path/to/file_directory"
php_value auto_prepend_file "file.php

如果在.htaccess中使用上述方法,请务必从php.ini中复制include_path并添加:/ path_to / file_directory,这样就不会丢失任何已经包含的内容.

或者,只需将:/ path / to / file_directory直接添加到php.ini中的include_path即可

更新

如果无法修改include_path,则可以尝试指定auto_prepend_file的相对路径.这应该有效,因为发送的文件路径的处理方式与使用require()调用的方式完全相同:

php_value auto_prepend_file "./file.php"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读