可以只传$a和$c吗
<?php
$a = new c;
class c
{
function __construct(){
$this->f(1,,1);//会报错
}
function f($a, $b = 'hello', $c)
{
if($a) echo $a;
if($b) echo $b;
if($c) echo $c;
}
}
?>Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
带默认值的函数参数应该放到最后.
再改不了f()方法的情况下,可以加个方法来实现
_f(1, 1); } public function f($a, $b = 'hello', $c) { if($a) echo $a; if($b) echo $b; if($c) echo $c; } public function _f() { $input = func_get_args(); $arguments = []; $reflection = new ReflectionMethod($this, 'f'); foreach ($reflection->getParameters() as $parameter) { $arguments[] = $parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : array_shift($input); } return call_user_func_array([$this, 'f'], $arguments); } } $c = new C();_f()方法接收到的参数,会依次传值给f()方法中没有默认值的参数。