php PHP中三点(...)的含义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41124015/
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
Meaning of Three dot (...) in PHP
提问by abu abu
What is the meaning of Three dot (...) in PHP ?
PHP 中的三点 (...) 是什么意思?
While I am installing Magento 2 in my Sever I got an error. Investigate the code and found that there is a Three dot (...), which is producing the error. I mentioned the code below
当我在服务器中安装 Magento 2 时,出现错误。查了一下代码,发现有一个三点(...),就是产生错误的。我提到了下面的代码
return new $type(...array_values($args));
回答by Saumya Rastogi
The ...$str
is called a splat operator in PHP.
在...$str
被称为在PHP图示操作。
This feature allows you to capture a variable number of arguments to a function, combined with "normal" arguments passed in if you like. It's easiest to see with an example:
此功能允许您为函数捕获可变数量的参数,如果您愿意,还可以结合传入的“普通”参数。用一个例子最容易看到:
function concatenate($transform, ...$strings) {
$string = '';
foreach($strings as $piece) {
$string .= $piece;
}
return($transform($string));
}
echo concatenate("strtoupper", "I'd ", "like ", 4 + 2, " apples");
// This would print:
// I'D LIKE 6 APPLES
The parameters list in the function declaration has the ...
operator in it, and it basically means " ... and everything else should go into $strings". You can pass 2 or more arguments into this function and the second and subsequent ones will be added to the $strings array, ready to be used.
函数声明中的参数列表中有...
操作符,它的基本意思是“......其他所有东西都应该进入 $strings”。您可以将 2 个或更多参数传递给此函数,第二个和后续参数将添加到 $strings 数组中,以备使用。
Hope this helps!
希望这可以帮助!
回答by rap-2-h
Every answer refers to the same blog post, besides them, here is the official documentation about variable-length argument lists:
每个答案都参考同一篇博文,除此之外,这里是关于可变长度参数列表的官方文档:
http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list
http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list
In PHP 5.6 and later, argument lists may include the ... token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array
在 PHP 5.6 及更高版本中,参数列表可能包含 ... 标记以表示该函数接受可变数量的参数。参数将作为数组传递给给定的变量
It seems "splat" operator is not an official name, still it's cute!
似乎“splat”运算符不是正式名称,但它仍然很可爱!
回答by bloodyKnuckles
There are TWO uses for the ellipsis (...) PHP token—think of them as packingan array and unpackingan array. Both purposes apply to function arguments.
有两种用途的省略号(...)PHP令牌他们的-think作为包装的阵列和拆包的数组。这两个目的都适用于函数参数。
Pack
盒
When defining a function, if you need a dynamic number of variables provided to the function (i.e., you don't know how many arguments will be provided to that function when called in the code) use the ellipsis (...) tokento capture all remaining arguments provided to that function into an array that is accessible inside the function block. The number of dynamic arguments captured by ellipsis (...) can be zero or more.
当定义一个函数,如果你需要的提供给函数的变量动态数(即,你不知道有多少参数将被提供给在代码中调用时功能)使用省略号(...)令牌来将提供给该函数的所有剩余参数捕获到可在函数块内访问的数组中。省略号 (...) 捕获的动态参数的数量可以为零或更多。
例如:
// function definition
function sum(...$numbers) { // use ellipsis token when defining function
$acc = 0;
foreach ($numbers as $nn) {
$acc += $nn;
}
return $acc;
}
// call the function
echo sum(1, 2, 3, 4); // provide any number of arguments
> 10
// and again...
echo sum(1, 2, 3, 4, 5);
> 15
// and again...
echo sum();
> 0
When packing is used in function instantiation, ellipsis (...) captures all remaining arguments, i.e., you can still have any number of initial, fixed (positional) arguments:
在函数实例化中使用打包时,省略号 (...) 捕获所有剩余参数,即,您仍然可以拥有任意数量的初始固定(位置)参数:
function sum($first, $second, ...$remaining_numbers) {
$acc = $first + $second;
foreach ($remaining_numbers as $nn) {
$acc += $nn;
}
return $acc;
}
// call the function
echo sum(1, 2); // provide at least two arguments
> 3
// and again...
echo sum(1, 2, 3, 4); // first two are assigned to fixed arguments, the rest get "packed"
> 10
Unpack
打开包装
Alternatively, when calling a function, if the arguments you provide to that function are previously combined into an array use the ellipsis (...) tokento convert that array into individual arguments provided to the function—each array element is assigned to the respective function argument variable named in the function definition.
或者,在调用函数时,如果您提供给该函数的参数先前已组合成一个数组,请使用省略号 (...) 标记将该数组转换为提供给该函数的单个参数——每个数组元素都分配给各自在函数定义中命名的函数参数变量。
function add($aa, $bb, $cc) {
return $aa + $bb + $cc;
}
$arr = [1, 2, 3];
echo add(...$arr); // use ellipsis token when calling function
> 6
$first = 1;
$arr = [2, 3];
echo add($first, ...$arr); // used with positional arguments
> 6
$first = 1;
$arr = [2, 3, 4, 5]; // array can be "oversized"
echo add($first, ...$arr); // remaining elements are ignored
> 6
Unpacking is particularly useful when using array functionsto manipulate arrays or variables.
在使用数组函数操作数组或变量时,解包特别有用。
For example, unpacking the result of array_slice:
例如,解包array_slice的结果:
function echoTwo ($one, $two) {
echo "$one\n$two";
}
$steaks = array('ribeye', 'kc strip', 't-bone', 'sirloin', 'chuck');
// array_slice returns an array, but ellipsis unpacks it into function arguments
echoTwo(...array_slice($steaks, -2)); // return last two elements in array
> sirloin
> chuck
回答by Lead Developer
To use this feature, just warn PHP that it needs to unpack the array into variables using the ... operator
. See herefor more details, a simple example could look like this:
要使用此功能,只需警告 PHP 它需要使用... operator
. 有关更多详细信息,请参见此处,一个简单的示例可能如下所示:
$email[] = "Hi there";
$email[] = "Thanks for registering, hope you like it";
mail("[email protected]", ...$email);
回答by yergo
Meaning is that it decomposes an associative array to a list. So you do not need to type N parameters to call a method, just one. If method allows a decomposed parameter and if parameters are of the same type.
意思是它将关联数组分解为列表。所以调用一个方法不需要输入N个参数,只需要一个。If 方法允许分解的参数,并且如果参数是相同类型的。
For me, the most important thing about splat operator is that it can help to typehint array parameters:
对我来说,splat 运算符最重要的一点是它可以帮助键入提示数组参数:
$items = [
new Item(),
new Item()
];
$collection = new ItemCollection();
$collection->add(...$items); // !
// what works as well:
// $collection->add(new Item());
// $collection->add(new Item(), new Item(), new Item()); // :(
class Item {};
class ItemCollection {
/**
* @var Item[]
*/
protected $items = [];
public function add(Item ...$items)
{
foreach ($items as &$item) {
$this->items[] = $item;
}
}
}
it saves some effort on type control, especially while working with huge collections or very object-oriented.
它在类型控制上节省了一些精力,尤其是在处理大量集合或非常面向对象的情况下。
Important to notice is that ...$array
do decompose an array despite the type of its items, so you can go the ugly way also:
需要注意的是,...$array
尽管数组的 items 类型不同,但还是要分解它,因此您也可以采用丑陋的方式:
function test(string $a, int $i) {
echo sprintf('%s way as well', $a);
if ($i === 1) {
echo('!');
}
}
$params = [
(string) 'Ugly',
(int) 1
];
test(...$params);
// Output:
// Ugly way as well!
But please don't.
但请不要。
回答by GhostCat
回答by Behrad Khodayar
It seems no one has mentioned it, so here to stay[It will also help Google (& Other SEs) guide devs who asking for Rest Parameters in PHP]:
似乎没有人提到它,所以留在这里[它也将帮助谷歌(和其他 SE)指导在 PHP 中要求Rest 参数的开发人员]:
As indicated hereits called Rest Parameterson JS & I prefer this meaningful naming over that splat thing!
正如这里所指出的,它在 JS 上被称为Rest 参数,我更喜欢这个有意义的命名而不是那个 splat 的东西!
In PHP, The functionality provided by ...argsis called Variadic functionswhich's introduced on PHP5.6. Same functionality was used to be implemented using func_get_args()
.
在 PHP 中,...args提供的功能称为Variadic 函数,它是在 PHP5.6 上引入的。使用func_get_args()
.
In order to use it properly, you should use rest parameters syntax, anywhere it helps reducing boilerplate code.
为了正确使用它,您应该在任何有助于减少样板代码的地方使用 rest 参数语法。
回答by hailong
I'd like to share a usage of this operator in Magento framework, where it instantiates objects with dynamic configurable parameters (thought XML config files).
我想在 Magento 框架中分享这个运算符的用法,它用动态可配置参数(思想 XML 配置文件)实例化对象。
As we can see the createObject
function from the following code snippet, it takes in an array of the arguments prepared for the object creation. Then it uses the ...
(three dots) operator to pass the array values as real arguments to the class's constructor.
正如我们createObject
从以下代码片段中看到的那样,它接受为创建对象准备的参数数组。然后它使用...
(三个点)运算符将数组值作为真正的参数传递给类的构造函数。
<?php
namespace Magento\Framework\ObjectManager\Factory;
abstract class AbstractFactory implements \Magento\Framework\ObjectManager\FactoryInterface
{
...
/**
* Create object
*
* @param string $type
* @param array $args
*
* @return object
* @throws RuntimeException
*/
protected function createObject($type, $args)
{
try {
return new $type(...array_values($args));
} catch (\TypeError $exception) {
...
}
}
...
}
回答by Bivek J.
it is splat or scatter operator in PHP
它是 PHP 中的 splat 或 scatter 运算符
reference: splat or scatter operator in PHP