如何在调用PHP函数时传入少于预期数量的参数?
我有一个运行正常的PHP函数:
<?php function my_test_function($par1, $par2, $par3) { $string = $par1.$par2.$par3; return $string; } echo my_test_function('Hello', 'how are', 'you'); ?>但当我这样调用该函数时:
echo my_test_function('Hello', 'how are');会触发如下错误:
[29-Jan-2023 10:29:45 UTC] PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function my_test_function(), 2 passed in /home/user/public_html/test_file.php on line 7 and exactly 3 expected in /home/user/public_html/test_file.php:2 Stack trace: #0 /home/user/public_html/test_file.php(7): my_test_function('Hello', 'how are') #1 {main} thrown in /home/user/public_html/test_file.php on line 2我希望能传入两个参数调用该函数,而非预期的三个,且不想将第三个参数设为空,请问有办法实现吗?
解决方案
下面提供几种满足需求的实现方式:
1. 可变参数实现(PHP 5.6+推荐)
使用...语法接收任意数量的参数,直接拼接所有传入内容,无需固定参数数量:
<?php function my_test_function(...$params) { return implode('', $params); } // 3个参数调用 echo my_test_function('Hello', 'how are', 'you'); // 输出 Hellohow areyou // 2个参数调用 echo my_test_function('Hello', 'how are'); // 输出 Hellohow are ?>
2. 兼容旧版PHP的参数判断
利用func_num_args()和func_get_args()动态处理参数数量,同时保留参数声明但设置一个不影响逻辑的默认值:
<?php function my_test_function($par1, $par2, $par3 = null) { $args = func_get_args(); // 只拼接实际传入的参数 return implode('', array_slice($args, 0, func_num_args())); } echo my_test_function('Hello', 'how are', 'you'); // 正常输出 echo my_test_function('Hello', 'how are'); // 无报错,输出前两个参数拼接结果 ?>
这里$par3 = null只是为了满足函数声明的参数数量要求,实际不会用到空值拼接。
3. 给第三个参数设置非空默认值
如果需要在缺省第三个参数时用某个非空值填充(比如空格),可以直接指定默认值:
<?php function my_test_function($par1, $par2, $par3 = ' ') { $string = $par1.$par2.$par3; return $string; } echo my_test_function('Hello', 'how are'); // 输出 Hellohow are echo my_test_function('Hello', 'how are', 'you'); // 输出 Hellohow areyou ?>
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

