php 一个函数的多次返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3451906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:49:14  来源:igfitidea点击:

Multiple returns from a function

php

提问by vincent

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

是否可以有一个具有两个返回值的函数,如下所示:

function test($testvar)
{
  // Do something

  return $var1;
  return $var2;
}

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

如果是这样,我如何能够分别获得每个回报?

采纳答案by dockeryZ

There is no way of returning 2 variables. Although, you canpropagate an array and return it; create a conditional to return a dynamic variable, etc.

没有办法返回 2 个变量。虽然,您可以传播一个数组并返回它;创建条件以返回动态变量等。

For instance, this function would return $var2

例如,这个函数将返回 $var2

function wtf($blahblah = true) {
    $var1 = "ONe";
    $var2 = "tWo";

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

In application:

在应用中:

echo wtf();
//would echo: tWo
echo wtf("not true, this is false");
//would echo: ONe

If you wanted them both, you could modify the function a bit

如果你想要它们,你可以稍微修改一下函数

function wtf($blahblah = true) {
    $var1 = "ONe";
    $var2 = "tWo";

    if($blahblah === true) {
      return $var2;
    }

    if($blahblah == "both") {
      return array($var1, $var2);
    }

    return $var1;
}

echo wtf("both")[0]
//would echo: ONe
echo wtf("both")[1]
//would echo: tWo

list($first, $second) = wtf("both")
// value of $first would be $var1, value of $second would be $var2

回答by Jasper

Technically, you can't return more than one value. However, there are multiple ways to work around that limitation. The way that acts most like returning multiple values, is with the listkeyword:

从技术上讲,您不能返回多个值。但是,有多种方法可以解决该限制。最像返回多个值的方式是使用list关键字:

function getXYZ()
{
    return array(4,5,6);
}

list($x,$y,$z) = getXYZ();

// Afterwards: $x == 4 && $y == 5 && $z == 6
// (This will hold for all samples unless otherwise noted)

Technically, you're returning an array and using listto store the elements of that array in different values instead of storing the actual array. Using this technique will make it feelmost like returning multiple values.

从技术上讲,您正在返回一个数组并使用list不同的值来存储该数组的元素,而不是存储实际的数组。使用这种技术会让它感觉最像返回多个值。

The listsolution is a rather php-specific one. There are a few languages with similar structures, but more languages that don't. There's another way that's commonly used to "return" multiple values and it's available in just about every language (in one way or another). However, this method will look quite different so may need some getting used to.

list解决方案是一种特定于 php的解决方案。有几种语言具有相似的结构,但更多的语言没有。还有另一种通常用于“返回”多个值的方法,它几乎适用于每种语言(以一种或另一种方式)。但是,这种方法看起来会大不相同,因此可能需要一些时间来适应。

// note that I named the arguments $a, $b and $c to show that
// they don't need to be named $x, $y and $z
function getXYZ(&$a, &$b, &$c)
{
    $a = 4;
    $b = 5;
    $c = 6; 
}

getXYZ($x, $y, $z);

This technique is also used in some functions defined by php itself (e.g. $countin str_replace, $matchesin preg_match). This might feel quite different from returning multiple values, but it is worth at least knowing about.

这种技术也用于由 php 本身定义的一些函数中(例如$countstr_replace 中$matchespreg_match 中)。这可能与返回多个值感觉完全不同,但至少值得了解。

A third method is to use an object to hold the different values you need. This is more typing, so it's not used quite as often as the two methods above. It may make sense to use this, though, when using the same set of variables in a number of places (or of course, working in a language that doesn't support the above methods or allows you to do this without extra typing).

第三种方法是使用一个对象来保存您需要的不同值。这是更多的打字,所以它不像上面的两种方法那样经常使用。但是,当在许多地方使用相同的一组变量时(或者当然,使用不支持上述方法或允许您无需额外输入即可执行此操作的语言),使用它可能是有意义的。

class MyXYZ
{
    public $x;
    public $y;
    public $z;
}

function getXYZ()
{
    $out = new MyXYZ();

    $out->x = 4;
    $out->y = 5;
    $out->z = 6;

    return $out;
}

$xyz = getXYZ();

$x = $xyz->x;
$y = $xyz->y;
$z = $xyz->z;

The above methods sum up the main ways of returning multiple values from a function. However, there are variations on these methods. The most interesting variations to look at, are those in which you are actually returning an array, simply because there's so much you can do with arrays in PHP.

以上方法总结了从函数返回多个值的主要方式。但是,这些方法存在差异。最有趣的变体是那些实际上返回数组的变体,这仅仅是因为在 PHP 中可以用数组做很多事情。

First, we can simply return an array and not treat it as anything but an array:

首先,我们可以简单地返回一个数组,而不将其视为数组以外的任何东西:

function getXYZ()
{
    return array(1,2,3);
}

$array = getXYZ();

$x = $array[1];
$y = $array[2];
$z = $array[3];

The most interesting part about the code above is that the code inside the function is the same as in the very first example I provided; only the code calling the function changed. This means that it's up to the one calling the function how to treat the result the function returns.

关于上面代码最有趣的部分是函数内部的代码与我提供的第一个示例中的代码相同;只有调用函数的代码发生了变化。这意味着如何处理函数返回的结果取决于调用函数的人。

Alternatively, one could use an associative array:

或者,可以使用关联数组:

function getXYZ()
{
    return array('x' => 4,
                 'y' => 5,
                 'z' => 6);
}

$array = getXYZ();

$x = $array['x'];
$y = $array['y'];
$z = $array['z'];

Php does have the compactfunction that allows you to do same as above but while writing less code. (Well, the sample won't have less code, but a real world application probably would.) However, I think the amount of typing saving is minimal and it makes the code harder to read, so I wouldn't do it myself. Nevertheless, here's a sample:

Php 确实具有compact允许您执行与上述相同但编写更少代码的功能的功能。(嗯,示例不会有更少的代码,但现实世界的应用程序可能会。)但是,我认为节省的打字量很少,而且会使代码更难阅读,所以我不会自己做。不过,这里有一个示例:

function getXYZ()
{
    $x = 4;
    $y = 5;
    $z = 6;

    return compact('x', 'y', 'z');
}

$array = getXYZ();

$x = $array['x'];
$y = $array['y'];
$z = $array['z'];

It should be noted that while compactdoes have a counterpart in extractthat could be used in the calling code here, but since it's a bad idea to use it (especially for something as simple as this) I won't even give a sample for it. The problem is that it will do "magic" and create variables for you, while you can't see which variables are created without going to other parts of the code.

应该注意的是,whilecompact确实有一个extract可以在此处的调用代码中使用的对应物,但由于使用它是一个坏主意(尤其是对于像这样简单的东西),我什至不会给出它的示例。问题是它会做“魔术”并为您创建变量,而您在不转到代码的其他部分的情况下无法看到创建了哪些变量。

Finally, I would like to mention that listdoesn't reallyplay well with associative array. The following will do what you expect:

最后,我想提一下,关联数组list并不能很好地发挥作用。以下将执行您期望的操作:

function getXYZ()
{
    return array('x' => 4,
                 'y' => 5,
                 'z' => 6);
}

$array = getXYZ();

list($x, $y, $z) = getXYZ();

However, the following will do something different:

但是,以下将做一些不同的事情:

function getXYZ()
{
    return array('x' => 4,
                 'z' => 6,
                 'y' => 5);
}

$array = getXYZ();

list($x, $y, $z) = getXYZ();

// Pay attention: $y == 6 && $z == 5

If you used listwith an associative array, and someone else has to change the code in the called function in the future (which may happen just about any situation) it may suddenly break, so I would recommend against combining listwith associative arrays.

如果您使用list关联数组,并且其他人将来必须更改被调用函数中的代码(这可能会在任何情况下发生)它可能会突然中断,因此我建议不要list与关联数组结合使用。

回答by Tim Fountain

In your example, the second return will never happen - the first return is the last thing PHP will run. If you need to return multiple values, return an array:

在您的示例中,第二次返回永远不会发生 - 第一次返回是 PHP 将运行的最后一件事。如果需要返回多个值,返回一个数组:

function test($testvar) {

    return array($var1, $var2);
}

$result = test($testvar);
echo $result[0]; // $var1
echo $result[1]; // $var2

回答by Nukesor

Since PHP 7.1 we have proper destructuringfor lists. Thereby you can do things like this:

自 PHP 7.1 起,我们对列表进行了适当的解构。因此,您可以执行以下操作:

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

解构是一个非常强大的工具。它也能够解构 key=>value 对:

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

Take a look at the new feature page for PHP 7.1:

看看 PHP 7.1 的新功能页面:

New features

新功能

回答by SztupY

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

在 PHP 5.5 中还有一个新概念:generators,你可以从一个函数中产生多个值:

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

$values = hasMultipleValues();
foreach ($values as $val) {
    // $val will first be "value1" then "value2"
}

回答by Jake N

Or you can pass by reference:

或者你可以通过引用传递:

function byRef($x, &$a, &$b)
{
    $a = 10 * $x;
    $b = 100 * $x;
}

$a = 0;
$b = 0;

byRef(10, $a, $b);

echo $a . "\n";
echo $b;

This would output

这将输出

100
1000

回答by Muhammad Raheel

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

extractcreates a variable for each member in the array, named after that member. You can therefore now access $modeland $data

extract为数组中的每个成员创建一个变量,以该成员命名。因此,您现在可以访问$model$data

回答by Apsar

Its not possible have two return statement. However it doesn't throw error but when function is called you will receive only first return statement value. We can use return of array to get multiple values in return. For Example:

它不可能有两个返回语句。但是它不会抛出错误,但是当函数被调用时,你只会收到第一个 return 语句值。我们可以使用数组的返回来获得多个值作为回报。例如:

function test($testvar)
{
  // do something
  //just assigning a string for example, we can assign any operation result
  $var1 = "result1";
  $var2 = "result2";
  return array('value1' => $var1, 'value2' => $var2);
}

回答by zzapper

You can return multiple arrays and scalars from a function

您可以从函数返回多个数组和标量

function x()
{
    $a=array("a","b","c");
    $b=array("e","f");
    return array('x',$a,$b);
}

list ($m,$n,$o)=x();

echo $m."\n";
print_r($n);
print_r($o);

回答by timdev

Functions, by definition, only return one value.

根据定义,函数只返回一个值。

However, as you assumed, that value can be an array.

但是,正如您所假设的,该值可以是一个数组。

So you can certainly do something like:

所以你当然可以做这样的事情:

<?PHP
function myfunc($a,$b){
   return array('foo'=>$a,'bar'=>$b);
}
print_r(myfunc('baz','bork'));

That said, it's worth taking a moment and thinking about whatever you're trying to solve. While returning a complex result value (like an array, or an object) is perfectly valid, if you're thinking is that "I want to return two values", you might be designing poorly. Without more detail in your question, it's hard to say, but it never hurts to stop and think twice.

也就是说,值得花点时间思考一下您要解决的问题。虽然返回复杂的结果值(如数组或对象)是完全有效的,但如果您认为“我想返回两个值”,那么您的设计可能很糟糕。如果你的问题没有更多细节,很难说,但停下来三思而后行永远不会有什么坏处。