what's the difference between return/echo json

2019-09-08 16:06发布

maybe this is a simple and stupid question.

As we know, echo just print the variable out, and in a php function return statnds for return something to the function invoker.

I notice someone use echo json_encode while others using return json_encode,

I return something to jquery, and using echo/return are both ok.

But when I find that almost everyone using echo json_encode, and why ?

Thanks.

4条回答
霸刀☆藐视天下
2楼-- · 2019-09-08 16:41

In standard PHP code, the output of echo is captured by the webserver and returned as part of the reponse.

return simply returns the value to the parent function. The parent function can do whatever it likes with the returned data including echo.

consider:

function return_some_text(){
   return 'this text is returned';
}

function echo_some_text(){
   echo 'this text is echoed';
}

//does nothing
return_some_text(); 

//'this text is echoed' appears in the response
echo_some_text();   

//'this text is returned' appears in the response because the return value is echoed.
echo return_some_text(); 

Remember, the return value of a function can be used in whatever way the caller sees fit. This includes echoing if the caller sees fit.

When you see return json_encode(...) that means that the calling function is going to do something with the data before it is output to the server.

查看更多
我只想做你的唯一
3楼-- · 2019-09-08 16:54

return will not give any response in case of using ajax where as echo will give you the response.If you are using server side scripting only the probably you dont need to echo it.Instead of it you can use return.

Look at this example and the way which the functions are called

function  myFun($value){
  return 'This is the value '.$value;
}

echo myFun(10);//Output This is the value 10
myFun(10);//Will not give you any output

function  myFun($value){
  echo 'This is the value '.$value;
}

myFun(10);//Output This is the value 10
echo myFun(10);//Output This is the value 10

In case of ajax

$.ajax({
        url     :   'mypage.php',
        type    :   "POST",
        success :   function(res){
          alert(res);
        }
 });

In mypage.php

 echo 'Hello';//This will send Hello to the client which is the response

but

return 'Hello';//Will not send anything.So you wont get any response
查看更多
该账号已被封号
4楼-- · 2019-09-08 16:54

return will simply return the variable without echoing it, where as echo will echo it out when it is called. If you are using AJAX you are better off with echo

查看更多
5楼-- · 2019-09-08 16:57

It depends the nature of php framework you are using

if you are using ajax and your framework does standard outputting by itself then, you can use return else you have to echo it by yourself

查看更多
登录 后发表回答