rest echo vs return in GET

2019-08-26 22:43发布

I am a newbie in php and rest and I'm trying to understand what is going on in my API when using echo vs return....

I've tried to get down to the simplest possible scenario to isolate an issue of my rest API not returning any value, so here is goes:

I have a test.php file on my server with following content:

<?php
    if(function_exists($_GET['t1'])) {
        echo $_GET['t1']();
    }
    else if(function_exists($_GET['t2'])) {
        return $_GET['t2']();
    }

    function test() {
        return json_encode("test...");
    }
?>

I then make a simple request using, as unique header 'Content-Type: application/json`

https://www.eswys.ch/tmp/test.php?t1=test
https://www.eswys.ch/tmp/test.php?t2=test

And results are, respectively

"test..." 
""

I really struggle to understand this, why is my returned value somehow "lost" - is there any explanation to this?!

2条回答
甜甜的少女心
2楼-- · 2019-08-26 23:20

return assigns a value to a function call (like a variable) and echo is simply output to the html page or possibly a terminal window.

查看更多
一纸荒年 Trace。
3楼-- · 2019-08-26 23:33

Returning from a function does not actually render any content to the response. You may have seen people returning data in different frameworks but the framework is actually echoing the data for you behind the scenes.

查看更多
登录 后发表回答