简体   繁体   中英

Why my function doesn't return anything with return

I am making a routing system. When I run the code, if the route is correct it will search for the route and call the function. This is how the router is runned. The code doesn't return any error so I do not know what went wrong.

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

And this is how I assigned the routes in a web.php file

<?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>";
});

The 404 error runs fine even though I used return . It echoes out just fine but the problem is the return statements. If I use echo the h1 would be printed out but if the functions uses return there would be no output. Why is that happening? Also I did try to echo out the returned statement but nothing happened as well.

public function run()
    {
        echo $this->router->run();
    }

you can not return the value directly if you don't want to echo it on the view.

try this instead

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

or this

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

read more about the print command [here] https://www.php.net/manual/en/function.print.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM