为什么我的函数没有返回任何返回值

时间:2021-01-09 04:24:20

标签: php return router

我正在制作一个路由系统。当我运行代码时,如果路线正确,它将搜索路线并调用该函数。这就是路由器的运行方式。代码没有返回任何错误,所以我不知道出了什么问题。

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();
    }

1 个答案:

答案 0 :(得分:-1)

如果不想在视图上回显,则不能直接返回值。

试试这个

.s

或者这个

Router::set404(function (){
      echo "Hi error<h1>404</h1>";
      return;
  });

阅读有关打印命令的更多信息 [此处]https://www.php.net/manual/en/function.print.php