You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP路由系统出现Undefined variable Framework Routing等报错求助

报错原因

你遇到的报错由以下几个问题共同导致:

  • 第一/第二个Notice:虽然你贴出的代码里第二行写的是$_SERVER,但报错提示变量_server未定义,说明实际运行的代码中变量名写错了大小写,PHP的超全局变量必须全大写,小写的$_server属于自定义变量,没有赋值自然为null,访问数组偏移就会触发第二个报错。
  • 第三个Undefined offset 1报错:当你访问站点根路径/时,用explode("/", $_SERVER['REQUEST_URI'])得到的数组结构为['', ''],此时直接访问$linkExplode[1]、$linkExplode[2]会因为索引不存在触发偏移报错。
  • 空值判断逻辑错误:你写的if (empty($linkExplode[1] && empty($linkExplode[2])))括号位置完全错误,empty函数内把两个判断逻辑合并成了布尔值,完全达不到你想要的判断两个参数是否为空的效果。
  • 控制器文件路径完全不匹配:file_exists判断的文件名拼接了Homecontroller后缀,require引入的又拼接了UserController后缀,两个路径都和你实际的控制器文件名HomeController.class.php、UserController.class.php不符,就算前面的报错修复了也会一直返回404。
修复方案

你可以直接使用.htaccess重写后传入的url参数解析路由,比解析REQUEST_URI更简单,修正后的src/index.php代码如下:

<?php
// 先获取重写后的url参数,默认值为home/index
$url = $_GET['url'] ?? 'home/index';
$linkExplode = explode('/', $url);
// 过滤空值重新索引数组
$linkExplode = array_values(array_filter($linkExplode));

$controller = ucfirst($linkExplode[0] ?? 'Home');
$method = $linkExplode[1] ?? 'index';

// 拼接正确的控制器文件路径
$controllerFile = "./Controllers/{$controller}Controller.class.php";
if (file_exists($controllerFile)) {
    require $controllerFile;
    $className = "{$controller}Controller";
    $class = new $className();

    if (method_exists($class, $method)) {
        $class->$method();
    } else {
        http_response_code(404);
        exit('404 Not found');
    }
} else {
    http_response_code(404);
    exit('404 Not found');
}

另外确认你的控制器文件存放路径为src/Controllers/,文件名分别为HomeController.class.php、UserController.class.php,和类名保持一致即可。

内容的提问来源于stack exchange,提问作者user17308599

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 04:36:03