PHP 致命错误:参数解包后无法使用位置参数 [英] PHP Fatal error: Cannot use positional argument after argument unpacking

查看:33
本文介绍了PHP 致命错误:参数解包后无法使用位置参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 可变数量的参数(使用 ...) 调用具有相同参数的另一个函数和一个新的在末尾.顺序很重要!以下示例仅用于演示.

I would like to write a function with variable number of parameters (using ...) that calls another function with the same arguments and a new one at the end. Order is important! The example below is just for demonstration.

function foo(...$params) {
    $extraVariable = 6;
    var_dump(...$params, $extraVariable);
}
foo(2, 4, 1, 4);

问题

当我运行它时,我收到以下错误消息:

Problem

When I run it, I get the following error message:

PHP 致命错误:第 3 行/home/user/main.php 中的参数解包后无法使用位置参数

PHP Fatal error: Cannot use positional argument after argument unpacking in /home/user/main.php on line 3

我怎样才能实现我的目标?

How can I achieve my goal?

推荐答案

tl;dr

设计不允许在参数后解包,但有两种解决方法:

tl;dr

Unpacking after arguments is not allowed by design, but there are 2 workarounds:

  • 从新元素创建一个数组并将其解包为保罗建议:

function foo(...$params) {
    $extraVariable = 6;
    var_dump(...$params, ...[$extraVariable]);
}

  • 将新元素推送到参数:

  • Push the new element to the params:

    function foo(...$params) {
        $extraVariable = 6;
        $params[] = $extraVariable;
        var_dump(...$args);
    }
    

  • PHP 根本不支持这一点.您可以查看检查此行为的单元测试:

    PHP simply doesn't support this. You can see the unit test that checks this behavior:

    --TEST--
    Positional arguments cannot be used after argument unpacking
    --FILE--
    <?php
    
    var_dump(...[1, 2, 3], 4);
    
    ?>
    --EXPECTF--
    Fatal error: Cannot use positional argument after argument unpacking in %s on line %d
    

    这篇关于PHP 致命错误:参数解包后无法使用位置参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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