【发布时间】:2021-04-14 18:29:30
【问题描述】:
我正在制作一个路由系统。当我运行代码时,如果路线正确,它将搜索路线并调用该函数。这就是路由器的运行方式。代码没有返回任何错误,所以我不知道出了什么问题。
public function run()
{
$method = $this->getRequestMethod();
$curUrl = $this->getCurrentUrl();
$match = $this->matchRoute($curUrl, $method) ?? false;
if ($match == false || $match == 0){
return $this->call404();
}
}
public function matchRoute($curUrl, $method, $quitAftRun = true)
{
$match = 0;
$fn = self::$routes[$method][$curUrl] ?? false;
if ($fn){
$this->invoke($fn); $match++;
}
return $match;
}
public function invoke($fn, $params = [])
{
if (is_callable($fn)){
call_user_func_array($fn, $params);
}
}
这就是我在 web.php 文件中分配路由的方式
<?php
use app\core\Router;
Router::get("/", function(){
echo "<h1>Home</h1>";
});
Router::get("/about", function(){
return "<h1>About</h1>";
});
Router::set404(function (){
return "Hi error<h1>404</h1>";
});
即使我使用了return,404 错误运行良好。它很好地呼应了,但问题是return 语句。如果我使用 echo 将打印出 h1 但如果函数使用 return 将没有输出。为什么会这样?我也尝试过回显返回的语句,但也没有发生任何事情。
public function run()
{
echo $this->router->run();
}
【问题讨论】: