Dual output function

First, let me start by saying that I am a real beginner, mainly learning PHP. Understanding programming patterns and semantics is more important to me than just learning syntax. I've done some research for what I'm about to ask, but I couldn't find any information on this. So, I thought ... What if I need to do the following ... Give the function multiple outputs to be passed 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's the best practice to achieve the same semantics?

More details: Let's say I want to call a function with one argument and return not only the value back to the same place where the argument was called, but also to another place or to some other part of the program. The value of a function with two exits at two different places, but the second place will not be a call, just an exit from a call made at the first place, returned at the same time with the same value as the first. So without calling it twice separately ... But rather, calling it once and outputting it twice in different places. The second output will be used to pass the result to another part of the program and therefore will not be suitable as a "call / input", but rather as an "exit" only from the value of "input". How can I achieve multiple outputs in functions?

If this seems like a silly question, I'm sorry. I couldn't find information anywhere. thanks in advance

+3


source to share


3 answers


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);

      



Now you have two arguments and the result of using this function for use in other functions.

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

      

+3


source


If the question is about returning multiple variables, it's simple:



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

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

      

0


source


You can either return an array of values ​​to the function:

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

      

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

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

      

0


source







All Articles