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.
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 includingecho
.consider:
Remember, the return value of a function can be used in whatever way the caller sees fit. This includes
echo
ing 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.return
will not give any response in case of using ajax where asecho
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
In case of ajax
In mypage.php
but
return
will simply return the variable without echoing it, where asecho
will echo it out when it is called. If you are using AJAX you are better off withecho
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