简体   繁体   中英

Function with two outputs

First, let me start by saying i'm a real beginner learning mostly PHP. Understanding the patterns and semantics of programming is more important to me than just learning the syntax. I did some research for what I'm going to ask, but I couldn't find any info about it. So, I was thinking... What if I need to do the following... Give a function multiple outputs to pass in other parts of the code. What is the name of this type of functionality (if it exists)? Or If it doesn't exist, why not? And what is the best practice to achieve the same semantic?

More details: Let's say I want to call a function with one argument and return not only the value back to that same argument call location, but also in another location or into some other part of the program. Meaning a function with two outputs in two different locations, but the second location wouldn't be a call, just an output from the call made in the first location, returned at the same time with the same value output as the first. So, not calling it twice separately... But rather calling once and outputting twice in different locations. The second output would be used to pass the result into another part of the program and therefore wouldn't be appropriate as a "call/input", but more as an "output" only from the "input" value. How can I achieve multiple outputs in functions?

If this seems like a stupid question, I'm sorry. I couldn't find the info anywhere. Thanks in advance

What you want to do is basically this (i'll make it a 'practical' example):

function add($number1, $number2)
{
  $result = $number1 + $number2;

  return array('number1' => $number1,'number2' => $number2,'result' => $result);
}

$add = add(5,6); // Returns array('number1' => 5, 'number2' => 6, 'result' => 11);

You now have the two arguments and the result of that function at your disposal to use in other functions.

some_function1($add['result']);
...
some_function2($add['number1']);

If the question is about returning more than one variables, it is simply:

function wtf($foobar = true) {
    $var1 = "first";
    $var2 = "second";

    if($foobar === true) {
      return $var2;
    }
    return $var1;
}

You can either have the function return an array of values:

function foo($bar) {
  $bat = 1;
  return [$bar, $bat];
}

Or you can pass an argument that tells it which value to return:

function foo($bar, $return_bar=false) {
  $bat = 1;
  return $return_bar ? $bar : $bat;
}

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