0

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?!

neggenbe
  • 1,697
  • 2
  • 24
  • 62
  • 1
    `return` return values in functions and class methods - it's not used to output stuff. `echo` outputs the variable to its best ability. eg. you could `return 'hello';` in a function and then use `echo functionName();` to get `'hello'`. When you're using `return` _outside_ of a function or a method nothing happens. – h2ooooooo Jul 20 '17 at 17:42
  • 1
    Possible duplicate of [What is the difference between PHP echo and PHP return in plain English?](https://stackoverflow.com/questions/9387765/what-is-the-difference-between-php-echo-and-php-return-in-plain-english) – kjdion84 Jul 20 '17 at 17:43
  • 1
    `echo` print the output & continue execution whereas `return` also print the output & exit from that function – Omi Jul 20 '17 at 17:44
  • @Omi that's just absolutely contradictory with all other comments... `return` does NOT print resutl, that's the key point here!!! – neggenbe Jul 20 '17 at 18:16

2 Answers2

2

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.

Jim Wright
  • 5,905
  • 1
  • 15
  • 34
0

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.

DraganAscii
  • 322
  • 1
  • 9