简体   繁体   中英

Defining a variable as part of a function

Im having trouble setting a variable as part of a function, im sure its down the syntax more than anything, what im trying to do is use a if/else statement and as part of it, to return a variable $Bname.

But im not sure how to set it.

My function is as follows

 function bestPriceFunc($var1, $var2) {
      if ($var1 < $var2) {
          return $var1;
          $Bname = 'will';
          return $Bname;

      } else {
          return $var2;
          $Bname = 'Lad';
          return $Bname;
      }
  }

is this the correct way to do it or could i just write return $Bname = 'Lad'; . Ive tried both but i getting an undefined variable error when i load the page

You can only use return once per function as it terminates the function the first time it is executed.

Try the following or if you don't need to return $var1 and $var2, simply remove those lines.

<?php
function bestPriceFunc($var1, $var2) {
    if ($var1 < $var2) {
        $Bname = 'will';
        return array($var1, $Bname);

    } else {
        $Bname = 'Lad';
        return array($var2, $Bname);
    }
}

$var = bestPriceFunc(3, 4);
$bnameoutput = $var[1];
?>

You are getting undefined errors when you attempt to use the $Bname variable because you are already returning $var1 and $var2 .

A return statement ends the function. Once you hit return $var1; or return $var2 the function ends and returns the specified variable. In order to return the $Bname variable, you need to get rid of the other returns.

Once you return $var; the function execution ends, meaning that the rest of the code is ignored, so $Bname is not set.

You also have two "return" in each function, I suggest having a lopk at how functions work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM