Home  >  Article  >  Backend Development  >  How to solve the problem of automatic loading failure of php class

How to solve the problem of automatic loading failure of php class

藏色散人
藏色散人Original
2021-09-21 09:17:152327browse

php类自动加载失败的解决办法:1、打开相应的PHP代码文件;2、添加“$class = str_replace("\\","/",$class);”代码即可。

How to solve the problem of automatic loading failure of php class

本文操作环境:windows7系统、PHP7.1版、Dell G3电脑。

如何解决php类的自动加载失败问题?

PHP 命名空间下的自动加载失败

场景描述

文件在本地win系统下测试无异常,代码如下:

function stu_autoload($class){


    if(file_exists($class.".php")){        require ( $class.".php");
    }else{        die("unable to autoload Class $class");
    }
}

spl_autoload_register("stu_autoload");

部署到Ubuntu服务器上异常,报错为 unable to autoload Class xxxxxx

解决方案

根据报错,发现 $class 的值需要形如 stuApp\dao\StuInfo 才可行, 文件路径需要将 \ 转义成 /,因此添加一行代码即可。

    $class = str_replace("\\","/",$class);

综上,修改后的自动加载代码如下:

function stu_autoload($class){
    //路径转义
    $class = str_replace("\\","/",$class);    if(file_exists($class.".php")){        require ( $class.".php");
    }else{        die("unable to autoload Class $class");
    }
}

spl_autoload_register("stu_autoload");

推荐学习:《PHP视频教程》  

The above is the detailed content of How to solve the problem of automatic loading failure of php class. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn