You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP可变参数函数参数报错:如何修复该问题?

修复PHP可变参数calculate函数的参数错误

代码中的核心错误及修复方案:

  • 直接拼接数组到字符串:func_get_args()返回参数数组,无法直接与字符串拼接,需用count(func_get_args())获取参数总数。
  • func_get_arg()使用错误:
    • func_get_arg()必须传入索引参数,且需先通过func_num_args()判断索引是否存在,避免参数不足时报错;
    • 打印所有参数需用复数形式func_get_args(),而非func_get_arg()。
  • foreach语法错误:
    • 遍历所有参数要基于func_get_args()数组;
    • PHP中endforeach是连写语法,不能写成end foreach。
  • 函数未闭合:函数定义末尾缺少},导致语法不完整。

修复后的完整代码

function calculate(){
    // 输出参数总数
    echo "Number of argument :" . count(func_get_args()) . "\n";
    
    // 安全获取索引为3的参数(索引从0开始)
    if (func_num_args() > 3) {
        echo "Argument index number 3 is " . func_get_arg(3) . "\n";
    } else {
        echo "Argument index number 3 does not exist\n";
    }
    
    // 打印所有参数数组
    print_r(func_get_args());
    
    $result = 0;
    // 遍历参数求和
    foreach(func_get_args() as $arg) :
        $result += $arg;
    endforeach;
    
    echo "Total result: " . $result . "\n";
}

calculate(10, 20, 30, 1502);

运行结果示例

Number of argument :4
Argument index number 3 is 1502
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 1502
)
Total result: 1562

内容的提问来源于stack exchange,提问作者Anass bouyardane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 00:20:55