pro*_*spk 16 php methods function
我是php的n00b.我正在学习默认参数,所以我做了这个功能.
function doFoo($name = "johnny"){
echo "Hello $name" . "<br />";
}
Run Code Online (Sandbox Code Playgroud)
我做了这些电话
doFoo();
doFoo("ted");
doFoo("ted", 22);
Run Code Online (Sandbox Code Playgroud)
前两个印刷了预期的即
Hello johnny
Hello ted
Run Code Online (Sandbox Code Playgroud)
但第三次电话也印了
Hello ted
Run Code Online (Sandbox Code Playgroud)
在为一个参数创建所有函数之后,我期待一个错误,而我用两个参数调用它.
为什么没有错误?
Tom*_*Tom 19
PHP不会在函数重载时抛出错误.
将比需要的更多的参数传递给函数并没有错。
如果你传递几个参数,你只会得到错误。
function test($arg1) {
var_dump($arg1);
}
test();
Run Code Online (Sandbox Code Playgroud)
以上将导致以下错误:
Uncaught ArgumentCountError:函数的参数太少...
如果您想获取第一个参数以及传递给函数的所有其他参数,您可以执行以下操作:
function test($arg1, ...$args) {
var_dump($arg1, $args);
}
test('test1', 'test2', 'test3');
Run Code Online (Sandbox Code Playgroud)
结果:
string(5) "test1" array(2) { [0]=> string(5) "test2" [1]=> string(5) "test3" }