php 等待函数
这是一些 PHP 代码示例;
<?php
function myFunc() {
echo "blue";
}
for ($i=1;$i<=5;$i++) {
echo "I like the colour " . myFunc() . "</br>";
}
?>
这会生成输出;
blueI like the colour
blueI like the colour
blueI like the colour
blueI like the colour
blueI like the colour
在我的实际项目中,myFunc 正在进行 MySQL 调用(如果提到这一点有任何区别的话)。我怎样才能让我的循环在继续之前等待该函数返回,否则输出将像上面那样乱序。
This is some example PHP code code;
<?php
function myFunc() {
echo "blue";
}
for ($i=1;$i<=5;$i++) {
echo "I like the colour " . myFunc() . "</br>";
}
?>
This generates the output;
blueI like the colour
blueI like the colour
blueI like the colour
blueI like the colour
blueI like the colour
In my actual project, myFunc is making an MySQL call (if it makes any difference mentioning that). How can I make my loop wait for that function to return before carrying on otherwise the output is out of order like above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
问题在于
myFunc()
在连接之前进行评估。从myFunc()
返回值并在循环中使用该值,而不是在myFunc()
中回显。The problem is that
myFunc()
is evaluated before concatenating. Return the value frommyFunc()
and use that in your loop, rather than echoing inmyFunc()
.尝试将代码更改为:
注意
return
而不是echo
。Try changing the the code to this:
Take note the
return
rather thanecho
.您不想在函数中使用
echo
。请改用return
。当您评估循环时,首先评估函数以查看是否有返回值要放入字符串中。由于您调用
echo
而不是return
,因此会发生来自函数的回显,然后发生来自循环的回显。You do not want to use
echo
in your function. Usereturn
instead.When you evalute the loop, the function is evaluated first to see if there is a return value to put into the string. Since you call
echo
and notreturn
, the echo from the function is happening and then the echo from the loop is happening.使用返回语句:
Use the return statement:
这不是你的问题,你的问题是你有两个行动。
结果字符串是“I like the color”之间的串联。 myFunc() 。 "",但在连接这些值之前,必须执行 myFunc()。
当您执行 myFunc 时,您正在向输出写入“blue”。
那么,结果是(对于每一行)。
蓝色我喜欢这个颜色
(首先,评估 myFunc() 然后将返回值 (void) 连接到静态字符串。
也许您想这样做:
?>
this is not your problem, your problem is that you have two actions.
The result string is the contcatenation between "I like the colour " . myFunc() . "", but before you can concatenate these values, you must execute myFunc().
When you execute myFunc, you are writing "blue" to the output.
then, the result are (for every line).
blueI like the colour
(first, evaluate myFunc() an then concatenate the return value (void) to the static string.
maybe you want to do that:
?>