为何PHP无参数函数传入参数时解释器不报错?
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 likefunc_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

