PHP中三点(...)的含义

时间:2016-12-13 14:51:41

标签: php

PHP中的三点(...)是什么意思?

当我在我的Sever中安装Magento 2时出现错误。调查代码,发现有一个三点(...),产生错误。我提到了下面的代码

return new $type(...array_values($args));

11 个答案:

答案 0 :(得分:119)

...$str称为splat operator in PHP

此功能允许您捕获函数的可变数量的参数,并结合传入的“普通”参数(如果您愿意)。用一个例子来看最简单:

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

函数声明中的参数列表中包含...运算符,它基本上意味着“......其他所有内容都应该进入$ strings”。您可以将2个或更多参数传递给此函数,第二个和后续参数将添加到$ strings数组中,随时可以使用。

希望这有帮助!

答案 1 :(得分:14)

每个答案都引用同一篇博文,除此之外,这里是关于可变长度参数列表的官方文档

http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list

  

在PHP 5.6及更高版本中,参数列表可能包含...标记,表示该函数接受可变数量的参数。参数将作为数组传递给给定变量

似乎" splat"操作员不是正式名称,它仍然很可爱!

答案 2 :(得分:4)

的含义是它将关联数组分解为列表。因此,您无需键入N个参数即可调用一个方法,只需调用一个即可。如果方法允许分解参数,并且参数类型相同。

对我来说,关于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;
        }
    }
} 

它节省了类型控制方面的工作,尤其是在处理庞大的集合或非常面向对象的情况下。

重要的是,...$array确实分解了数组,尽管其类型不同,因此您也可以采用丑陋的方式:

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!

但是请不要。

答案 3 :(得分:3)

这就是所谓的“splat”运算符。基本上,这个东西转化为“任意数量的论点”; PHP 5.6引入

有关详细信息,请参阅here

答案 4 :(得分:3)

要使用此功能,只需警告PHP需要使用... operator将数组解压缩到变量中。有关详细信息,请参阅here,一个简单示例可能如下所示:

$email[] = "Hi there";
$email[] = "Thanks for registering, hope you like it";

mail("someone@example.com", ...$email);

答案 5 :(得分:2)

似乎没有人提及它,因此请留在这里[这也将帮助Google(和其他SE)引导要求在PHP中使用 Rest参数 的开发人员] :

As indicated here在JS上称为 Rest Parameters ,我更喜欢这种有意义的命名方式,而不是那些简陋的东西!

在PHP中,由 ... args 提供的功能称为Variadic functions,该功能是在PHP5.6上引入的。曾经使用func_get_args()实现相同的功能。

为了正确使用它,您应该在任何有助于减少样板代码的地方使用rest参数语法。

答案 6 :(得分:2)

PHP 7.4 中,省略号也是 Spread运算符

$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', 'watermelon'];

来源:https://wiki.php.net/rfc/spread_operator_for_array

答案 7 :(得分:1)

我想在Magento框架中共享此操作符的用法,该操作符使用动态可配置参数(思想XML配置文件)实例化对象。

从下面的代码片段中我们可以看到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) {
            ...
        }
    }

    ...

}

答案 8 :(得分:1)

ellipsis (...) PHP token有两种用途-将它们视为包装数组和解压缩数组。这两个目的都适用于函数参数。


包装

在定义函数时,如果需要为函数提供动态数量的变量(即,您不知道在代码中调用时将向该函数提供多少个参数),请使用ellipsis (...) token将提供给该函数的所有剩余参数捕获到该函数块内部可访问的数组中。省略号(...)捕获的动态参数的数量可以为零或更多。

For example

// 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

在函数实例化中使用打包时,省略号(...)会捕获所有其余参数,即,您仍然可以具有任意数量的初始,固定(位置)参数:

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

打开包装

或者,在调用函数时,如果您向该函数提供的参数先前已合并到数组中,请使用ellipsis (...) token将该数组转换为提供给该函数的单个参数-每个数组元素都分配给函数定义中命名的各个函数参数变量。

For example:

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

使用array functions处理数组或变量时,解压缩特别有用。

例如,解压缩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

答案 9 :(得分:1)

它是PHP中的splat或散点运算符

参考:splat or scatter operator in PHP

答案 10 :(得分:0)

版本5.6添加了splat运算符或有时称为参数解压缩。 splat运算符在参数前3个点。 splat运算符允许用户传递任意数量的参数。然后,PHP将任意参数转换为数组。

那么使用splat运算符和数组或关联数组有什么区别。您可以指定分配给splat运算符的对象的数据类型,如果它们与php不匹配,则会抛出错误。

function addItemsToCart(CartItem ...$cartItems) {
    //$cartItems is an array of CartItem objects
}

$cartItem1 = new CartItem();
$cartItem2 = new CartItem();
$cartItem3 = new CartItem();

addItemsToCart($cartItem1, $cartItem2, $cartItem3);

ref:Here