PHP echo 和 PHP return 用纯英语有什么区别?
是的,我已经用谷歌搜索了这个问题,甚至参考了我的教科书(Don Gosselin 的 PHP),但我似乎真的无法理解其中的解释.
Yes, I have googled this question and even referred to my textbook (PHP by Don Gosselin) but I seriously can't seem to understand the explanation.
据我了解:
echo = 显示函数的最终结果
echo = shows the final result of a function
return = 从函数返回值
return = returns the value from a function
我在以下函数中同时应用了 echo
和 return
我看不到使用 return
的区别或有效性"回声
.
I applied both echo
and return
in the following functions I can't see the difference or the 'effectiveness' of using return
instead of echo
.
<?php
echo "<h1 style='font-family:Helvetica; color:red'>Using <em>echo</em></h1>";
function add1($x, $y){
$total = $x + $y;
echo $total;
}
echo "<p>2 + 2 = ", add1(2, 2), "</p>";
echo "<h1 style='font-family:Helvetica; color:red'>Using <em>return</em></h1>";
function add2($x, $y){
$total = $x + $y;
return $total;
}
echo "<p>2 + 2 = ", add2(2, 2), "</p>";
?>
两者都显示结果!我不明白什么?
Both display the result! What am I not understanding?
推荐答案
我将给出一个完全非技术性的答案.
I'm going to give a completely non-technical answer on this one.
假设有一个名叫 Sally Function 的女孩.你想知道她喜不喜欢你.所以,既然你在上小学,你决定给 Sally 一个便条(用参数调用函数),询问她是否喜欢你.现在你打算做的是问她这个,然后告诉每个人她告诉你什么.相反,你问她,然后 她 告诉每个人.这相当于返回(您获取信息并用它做某事)与她的回应(在您无法控制的情况下告诉所有人).
Let's say that there is a girl named Sally Function. You want to know if she likes you or not. So since you're in grade school you decide to pass Sally a note (call the function with parameters) asking her if she likes you or not. Now what you plan on doing is asking her this and then telling everyone what she tells you. Instead, you ask her and then she tells everyone. This is equivalent to returning (you getting the information and doing something with it) vs her echoing (telling everyone without you having any control).
在你的情况下,发生的事情是,当 Sally echo
时,她正在从你手中夺走控制权并说我现在要告诉人们这件事",而不是你能够采取她的回应并做你想做的事.然而,最终的结果是,你在同时告诉别人,因为你在重复她已经回应但没有回复的内容(她在 你 告诉你的班级时打断了你她喜不喜欢你)
In your case what is happening is that when Sally echo
s she is taking the control from you and saying "I'm going to tell people this right now" instead of you being able to take her response and do what you wanted to do with it. The end result is, however, that you were telling people at the same time since you were echoing what she had already echoed but didn't return (she cut you off in the middle of you telling your class if she liked you or not)
相关文章