Categories
PHP

PHP 8 新特性:命名参数

PHP 8 新增了语言特性:命名参数(Named Arguments)。以往只能按照函数定义的顺序传递参数,现在可以指定参数名称自定义顺序。并且可以跳过带默认值的参数。

正文

我们举例说明。

我们先定义一个函数,接受三个参数。函数中直接将实际接收到的参数打印出来。代码如下:

function findProducts($tag, $type = 1, $status = 1) {
    printf("Params > tag: %s, type: %d, status: %d\n\n", $tag, $type, $status);
}

在 PHP 7 中,我们调用函数时,不允许带参数名称。如下:

findProducts("fav", 1, 2);

// 输出
Params > tag: fav, type: 1, status: 2

在 PHP 8 中,我们可以像下面这样。

  • 指定默认顺序参数名,效果同上
findProducts(tag: "fav", type: 1, status: 2);

// 输出
Params > tag: fav, type: 1, status: 2
  • 参数一二顺序换位,不受影响
findProducts(type: 1, tag: "fav", status: 2);

// 输出
Params > tag: fav, type: 1, status: 2
  • 跳过带有默认值的参数 type。
findProducts(tag: "fav", status: 2);

// 输出
Params > tag: fav, type: 1, status: 2
  • 无参数名和带参数名混合使用
findProducts("fav", status: 2);

// 输出
Params > tag: fav, type: 1, status: 2

话外

除了 PHP,还有哪些语言支持命名参数呢?

Python:见《Expressions -> Calls》、《Python Keyword Arguments

C# 4:见《命名实参和可选实参

Swift:见《Functions -> Functions With Multiple Parameters

参考资料:

(完)

扫码阅读和分享

Leave a Reply

Your email address will not be published. Required fields are marked *