使用splat将函数参数传递和接收为关联数组。

huangapple go评论75阅读模式
英文:

Using splat to pass and receive function arguments with an associative array

问题

如果我这样做:

function myfunc(mixed ...$var) {
  dump($var);
}

$param = [
  'one' => 1,
  'two' => 2,
];
myfunc(...$param);

那么输出结果如下:

^ array:2 [
  "one" => 1
  "two" => 2
]

这个特性很有用,因为它保留了数组键,但是我在https://www.php.net/manual/en/functions.arguments.php的文档中没有找到相关信息。

这是怎么回事?这是有意设计的文档行为,还是将来的PHP版本中可能消失的怪异行为?

英文:

If I do this:

function myfunc(mixed ...$var) {
  dump($var);
}

$param = [
  'one' => 1,
  'two' => 2,
];
myfunc(...$param);

Then the output is:

^ array:2 [
  "one" => 1
  "two" => 2
]

It's useful that the array keys are preserved, but I don't see anything about this in the documentation at https://www.php.net/manual/en/functions.arguments.php.

What's happening here? Is it documented behaviour that's by design, or a quirk that could vanish in a future version of PHP?

答案1

得分: 4

这里有两个概念,不要混淆:

  1. 参数/数组解包

    myfunc(...$param);

  2. 可变长度参数列表

    function myfunc(mixed ...$var)

当你调用函数时,第一个运算符将数组解包成参数列表。给定数组是关联数组时,它会解包成一个命名参数列表。

第二个标记将参数列表重新组合成数组,因此你可以得到函数参数的数组形式。如果参数是命名的,你将获得一个关联数组。你可以通过在$param之前和之后添加一些参数来看它是如何工作的,例如:

myfunc('positional', ...$param, named: 'value');

直到PHP 8才允许使用字符串键来解包数组,有了命名参数的支持。

如果你想查找PHP的标准,你需要在PHP的rfc网站上搜索,这里是与问题相关的文章:

英文:

There are 2 concepts here, don't be confused:

  1. Argument/Array unpacking

    myfunc(...$param);
    
  2. Variable-length argument lists

    function myfunc(mixed ...$var)
    

When you call your function, the first operator unpacks the array into an argument list. Given the array is associative, it unpacks into a named argument list.

The second token groups the argument list back into array, so you get arguments of your function in the form of array. Given arguments are named, you get an associative array. You can see how it works by adding some arguments before and after $params, like

myfunc('positional', ...$param, named: 'value');

Unpacking array with string keys is not always allowed until PHP 8, with the support of Named Arguments.

FYI if you want to search the standards of PHP, you need to search in the rfc site of PHP, here are the articles related to the question:

huangapple
  • 本文由 发表于 2023年3月9日 18:44:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75683511.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定