PHP7.4新语法:数组延展操作符

2019-07-0515:17:47编程语言入门到精通Comments2,766 views字数 791阅读模式

数组表达式中对展开操作符(Spread Operator)支持的RFC投票是绝大多数人赞同将此功能添加到PHP7.4。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

扩展运算符支持参数解包首先存在于PHP5.6中,并且此RFC扩展了对数组的使用;扩展可以支持Traversable的数组和对象。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

这是RFC的一个基本示例:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

$parts = ['apple''pear'];$fruits = ['banana''orange', ...$parts'watermelon'];文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

// ['banana', 'orange', 'apple', 'pear', 'watermelon'];文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

以下是进一步的示例:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

$arr1 = [1, 2, 3];$arr2 = [...$arr1]; // [1, 2, 3]文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

$arr3 = [0, ...$arr1]; // [0, 1, 2, 3]文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

$arr4 array(...$arr1, ...$arr2, 111); // [1, 2, 3, 1, 2, 3, 111]文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

$arr5 = [...$arr1, ...$arr1]; // [1, 2, 3, 1, 2, 3]文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

function getArr() {文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

  return ['a''b'];文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

}文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

$arr6 = [...getArr(), 'c']; // ['a', 'b', 'c']文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

$arr7 = [...new ArrayIterator(['a''b''c'])]; // ['a', 'b', 'c']文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

function arrGen() {文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

    for($i = 11; $i < 15; $i++) {文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

        yield $i;文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

    }文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

}文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

$arr8 = [...arrGen()]; // [11, 12, 13, 14]文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

不支持字符串键;你只能使用索引数组。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

RFC的作者对关键的支持做了如下说明:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

为了使行为与argument unpacking一致,不支持字符串键。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

遇到字符串键后,将抛出可恢复的错误。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13977.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/13977.html

Comment

匿名网友 填写信息

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

确定