欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php 用spl_autoload时,传来的命名空间分割符是,这个在linux上出问题

程序员文章站 2022-05-02 14:15:15
...

use CoreConfig;
use CoreRouter;

class Framework {

public static function init() {
    require_once (__DIR__ . '/functions.php');
    // 自动加载设置
    spl_autoload_register('self::loadClass');
    define("ROOT", getcwd());
    define('APP', ROOT . '/' . Config::get('app.app_name'));
    // 设置时区
    ini_set('date.timezone', Config::get('app.timezone'));
    $router = new Router();
    // 加载路由设置
    require_once (APP . '/routes.php');
    $router->dispatch();
}

public static function loadClass($className) {
    // linux上路径
    $className = str_replace("\\", "/", $className);
    $filename = ROOT . "/" . $className . ".php";
    if(is_file($filename))
        require_once($filename);
    else
        throw new \Exception("$filename Is Not Found");
}

}

然后我用str_replace函数替换,总感觉这样不是最好的方案

回复内容:

use CoreConfig;
use CoreRouter;

class Framework {

public static function init() {
    require_once (__DIR__ . '/functions.php');
    // 自动加载设置
    spl_autoload_register('self::loadClass');
    define("ROOT", getcwd());
    define('APP', ROOT . '/' . Config::get('app.app_name'));
    // 设置时区
    ini_set('date.timezone', Config::get('app.timezone'));
    $router = new Router();
    // 加载路由设置
    require_once (APP . '/routes.php');
    $router->dispatch();
}

public static function loadClass($className) {
    // linux上路径
    $className = str_replace("\\", "/", $className);
    $filename = ROOT . "/" . $className . ".php";
    if(is_file($filename))
        require_once($filename);
    else
        throw new \Exception("$filename Is Not Found");
}

}

然后我用str_replace函数替换,总感觉这样不是最好的方案

你的方法是对的,不过通常不是替换成/,而是使用常量DIRECTORY_SEPARATOR

使用通用分隔符,DIRECTORY_SEPARATOR

相关标签: php