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

为何PHP无参数函数传入参数时解释器不报错?

Why PHP Doesn’t Throw an Error for the First Function Call

Great question! Let’s break down why your first code snippet runs without any warnings or errors, even though you’re passing an argument to a function that doesn’t define any parameters.

The Short Answer

In PHP, functions defined with no declared parameters will happily accept any number of arguments when called—this is intentional behavior built into the language.

The Longer Explanation

When you write:

function ab(){ echo "yes"; }
ab(2);

PHP doesn’t see the extra 2 as a problem because:

  • PHP has built-in support for handling variable numbers of arguments, even if you don’t explicitly define them in the function signature. You could, for example, modify the ab() function to access that extra argument using functions like func_get_args():
    function ab(){
        $args = func_get_args();
        echo "yes, and you passed: " . $args[0];
    }
    ab(2); // Outputs: yes, and you passed: 2
    
  • The interpreter assumes that if you didn’t declare parameters, you might still want to handle incoming arguments dynamically. Unlike your second snippet (where you explicitly declared two required parameters), there’s no expectation set for how many arguments the function should receive.

Contrast with Your Second Snippet

In the second case:

function ab($a, $b){ echo "yes"; }
ab(2);

You’ve explicitly told PHP that ab() requires two parameters. When you only pass one, PHP throws a warning because it can’t fulfill the requirement you defined—this is the expected, strict behavior for functions with declared parameters.


内容的提问来源于stack exchange,提问作者Vijay Dohare

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:16:10