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:07

I think eliego has explained the answer clearly. But if you want to return both values, put them into a array and return it.

function test($testvar)
{
  // do something

  return array('var1'=>$var1,'var2'=>$var2);
//defining a key would be better some times   
}

//to access return values

$returned_values=$this->test($testvar);

echo $testvar['var1'];
echo $testvar['var2'];
查看更多
心情的温度
3楼-- · 2018-12-31 19:08

Best Practice is to put your returned variables into array and then use list() to assign array values to variables.

<?php

function add_subt($val1, $val2) {
    $add = $val1 + $val2;
    $subt = $val1 - $val2;

    return array($add, $subt);
}

list($add_result, $subt_result) = add_subt(20, 7);
echo "Add: " . $add_result . '<br />';
echo "Subtract: " . $subt_result . '<br />';

?>
查看更多
刘海飞了
4楼-- · 2018-12-31 19:09

I have implement like this for multiple return value PHP function. be nice with your code. thank you.

 <?php
    function multi_retun($aa)
    {
        return array(1,3,$aa);
    }
    list($one,$two,$three)=multi_retun(55);
    echo $one;
    echo $two;
    echo $three;
    ?>
查看更多
明月照影归
5楼-- · 2018-12-31 19:10

yes, you can use an object :-)

but the simplest way is to return an array:

return array('value1','value2','value3','...');
查看更多
伤终究还是伤i
6楼-- · 2018-12-31 19:10

Some might prefer returning multiple values as object:

function test() {
    $object = new stdClass();

    $object->x = 'value 1';
    $object->y = 'value 2';

    return $object;
}

And call it like this:

echo test()->x;

Or:

$test = test();
echo $test->y;
查看更多
裙下三千臣
7楼-- · 2018-12-31 19:13

I know that I am pretty late, but there is a nice and simple solution for this problem.
It's possible to return multiple values at once using destructuring.

function test()
{
    return [ 'model' => 'someValue' , 'data' => 'someothervalue'];
}

Now you can use this

$result = test();
extract($result);

extract creates a variable for each member in the array, named after that member. You can therefore now access $model and $data

查看更多
登录 后发表回答