【问题标题】:Why my function doesn't return anything with return为什么我的函数没有返回任何内容
【发布时间】: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();
    }

【问题讨论】:

    标签: php return router


    【解决方案1】:

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

    试试这个

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

    或者这个

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

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

    【讨论】:

    • 我确实回显了返回的语句,但它没有返回任何内容
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    相关资源
    最近更新 更多