数组声明中的PHP传播语法 [英] PHP Spread Syntax in Array Declaration

查看:77
本文介绍了数组声明中的PHP传播语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP支持各种函数的传播语法a>.

PHP supports the spread syntax for variadic functions.

在JavaScript中,您可以使用传播语法来执行:

In JavaScript, you can use the spread syntax to do this:

var a = [1, 2];
var b = [...a, 3, 4];
console.log(b); // [1, 2, 3, 4]

但是,尝试在PHP中执行此操作:

However, trying to do this in PHP:

$a = [1, 2];
$b = [...$a, 3, 4];
var_dump($b);die;

导致此错误:

解析错误:语法错误,意外的'...'(T_ELLIPSIS),预期为']'

Parse error: syntax error, unexpected '...' (T_ELLIPSIS), expecting ']'

PHP是否以这种方式使用传播语法?如果是这样,是否有一种同样优雅的方法来达到相同的效果?

Is using the spread syntax this way not allowed in PHP? If so, is there an equally-as-elegant way to achieve the same effect?

推荐答案

数组RFC 已在PHP 7.4中实现:

The spread operator in the arrays RFC has been implemented in PHP 7.4:

$ary = [3, 4, 5];
return [1, 2, ...$ary]; // same as [1, 2, 3, 4, 5]

注意:解压缩的数组/Traversable只能具有整数键.对于字符串键,仍然需要array_merge().

Caveat: The unpacked array/Traversable can only have integer keys. For string keys array_merge() is still required.

这篇关于数组声明中的PHP传播语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆