开发者

php wait for function

开发者 https://www.devze.com 2023-03-15 04:06 出处:网络
This is some example PHP code code; <?php function myFunc() { echo \"blue\"; } for ($i=1;$i<=5;$i++) {

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 m开发者_如何学运维ake my loop wait for that function to return before carrying on otherwise the output is out of order like above.


The problem is that myFunc() is evaluated before concatenating. Return the value from myFunc() and use that in your loop, rather than echoing in myFunc().


Try changing the the code to this:

<?php
function myFunc() {
    return "blue";
}

for ($i=1;$i<=5;$i++) {
    echo "I like the colour " . myFunc() . "</br>";
}
?>

Take note the return rather than echo.


You do not want to use echo in your function. Use return 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 not return, the echo from the function is happening and then the echo from the loop is happening.


Use the return statement:

 <?php
 function myFunc() {
     return "blue";
 }


  <?php
  function myFunc() {
      return "blue";
  }

  for ($i=1;$i<=5;$i++) {
      $color = myFunc();
      echo "I like the colour " . $color . "</br>";
  }
  ?>


this is not your problem, your problem is that you have two actions.

you are concatenating a string
you are calling a function.

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:

<?php    
function myFunc() {
        return "blue";
    }
for ($i=1;$i<=5;$i++) {
    echo "I like the colour " . myFunc() . "</br>";
}

?>

0

精彩评论

暂无评论...
验证码 换一张
取 消