Multiple returns from function

2018-12-31 18:26发布

Is it possible to have a function with 2 returns like this:

function test($testvar)
{
  // do something

  return $var1;
  return $var2;
}

If so, how would I be able to get each return separately?

标签: php
28条回答
裙下三千臣
2楼-- · 2018-12-31 19:20

You can get values of two or more variables by setting them by reference

function t(&$a, &$b) {
    $a = 1;
    $b = 2;
}


t($a,$b);

echo $a . '  ' . $b;

output:

1 2
查看更多
还给你的自由
3楼-- · 2018-12-31 19:20

use globals like:

<?php

function t($a) 
{
 global $add, $noadd;
 $add=$a+$a;
 $noadd=$a;
}

$a=1;
t($a);
echo $noadd." ".$add;
?>

This will echo 1 2

查看更多
不流泪的眼
4楼-- · 2018-12-31 19:21

Add all variables in an array and then finally return the array.

function test($testvar)
{
  // do something
  return array("var1" => $var1, "var2" => @var2);
}

And then

$myTest = test($myTestVar);
//$myTest["var1"] and $myTest["var2"] will be usable
查看更多
不再属于我。
5楼-- · 2018-12-31 19:23

Since Php 7.1 we have proper destructuring for lists. Thereby you can do things like this:

$test = [1,2,3,4];
[$a, $b, $c, $d] = $test;
echo($a);
> 1
echo($d);
> 4

In a function this would look like this:

function multiple_return() {
    return ['this', 'is', 'a', 'test'];
}

[$first, $second, $third, $fourth] = multiple_return();
echo($first);
> this
echo($fourth);
> test

Destructuring is a very powerful tool. It's capable of destructuring key=>value pairs as well

["a" => $a, "b" => $b, "c" => $c] = ["a" => 1, "b" => 2, "c" => 3];

Take a look at the new feature page: http://php.net/manual/de/migration71.new-features.php

查看更多
零度萤火
6楼-- · 2018-12-31 19:24

yes and no, you can't return more than one variable / object, but as you suggest, you can put them into an array and return that, there is no limit to the nesting of arrays so you can just package them up that way to return

查看更多
大哥的爱人
7楼-- · 2018-12-31 19:25

In PHP 5.5 there is also a new concept: generators, where you can yield multiple values from a function:

function hasMultipleValues() {
    yield "value1";
    yield "value2";
}

$values = hasMultipleValues();
foreach ($values as $val) {
    // $val will first be "value1" then "value2"
}
查看更多
登录 后发表回答