Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/magento/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php函数';s必需的参数混淆_Php_Function_Arguments - Fatal编程技术网

php函数';s必需的参数混淆

php函数';s必需的参数混淆,php,function,arguments,Php,Function,Arguments,我正在寻找PHP函数签名中所需参数的确切类型 仅使用NULL初始化参数是否使其成为可选参数?i、 e function foo($optional=NULL, $OptionalOrRequired="Optional Or Required", $required){} 我对第二个参数感到困惑,它是必需参数还是可选参数 更新 我使用reflection获取函数的所有必需参数 public function getPlayer($params=3, $c){} // results $refl

我正在寻找PHP函数签名中所需参数的确切类型

仅使用NULL初始化参数是否使其成为可选参数?i、 e

function foo($optional=NULL, $OptionalOrRequired="Optional Or Required", $required){}
我对第二个参数感到困惑,它是必需参数还是可选参数

更新

我使用
reflection
获取函数的所有必需参数

public function getPlayer($params=3, $c){}
// results
$reflection->getNumberOfParameters()            ->   2
$reflection->getNumberOfRequiredParameters()    ->   2 // it should be one

public function getPlayer($params=3, $c, $x=NULL)
// results
$reflection->getNumberOfParameters()            ->   3
$reflection->getNumberOfRequiredParameters()    ->   2
在我得到的一个答案中,默认值先于必需值,这就是反射函数返回所需参数的错误计数的原因吗


谢谢

在PHP中,可选参数后面不能有必需的参数。可选参数必须始终遵循所需参数(如果有)。任何提供了默认值的参数(例如,
$param='default'
)都是可选的,并且任何没有默认值的参数都是必需的。

进一步了解我的评论

function test($required, $optional = null)
{

}

test(); // throws an error stating $required is missing
test('a'); // sets $required to 'a' and $optional is null
test('a', 'b'); // sets $required to 'a' and $optional to 'b'

“可选”参数只是具有默认值的参数,无论该值是否为
null
false
,字符串(等)都无关紧要-如果函数参数具有默认值,则它是可选的

但是,将可选参数放在必需参数之前是没有意义的,因为您必须给先前的参数一些值(即使它是
null
)才能“到达”必需参数-因此,最后一个“必需”参数之前的所有参数都是有效必需的

一些例子:

// Bad
function bad($optional = 'literally anything', $required) {}

bad('required arg');              // This breaks - 'missing argument 2'
bad('something', 'required arg'); // This works - both parameters are needed

// Good
function($required, $optional = 'literally anything') {}

good('required arg');              // This works just fine, last argument has a default
good('required arg', 'something'); // Also works fine, overrides 'literally anything'
更新:反思

如上所述,将“可选”参数置于所需参数之前实际上会使该“可选”参数成为所需参数,因为必须为其指定一个值才能满足方法签名


例如,如果第一个参数有默认值,而第二个参数没有(如上面的
bad
函数),我们需要传递第二个参数,因此我们也需要传递第一个参数,因此两者都是“必需的”。如果后续参数具有默认值,则仍然只需要前2个参数。

基本上,您在函数声明中省略了参数的右侧,即
=null
,则它是必需的,否则如果未提供,该参数采用您在参数声明右侧指定的默认值。感谢您的快速回复Gavin,我实际上对我在第二个参数中使用的空值与实际值感到困惑。在给定的方法中,签名是第二个参数可选还是必需?可选,因为您已经为它提供了默认值,用户在调用它时是否应该不提供值。这不是OP所说的。他对一个函数感到困惑,它的可选参数先出现,然后是必需的参数。例如:
功能测试($optional=null,$required)