php函数的必选参数混淆 [英] php function's required parameter confusion
问题描述
我正在 PHP 函数签名中寻找 必需参数
的确切类型
I am looking for the exact type of a Required Parameter
in a PHP Function signature
仅使用 NULL 初始化参数是否使其成为可选参数?即
Does initializing a parameter only with NULL makes it an optional? i.e
function foo($optional=NULL, $OptionalOrRequired="Optional Or Required", $required){}
我对第二个参数感到困惑,它是必需参数还是可选参数?
I am confused about the 2nd argument, does it comes in Required or Optional parameter?
更新
我正在使用 reflection
来获取函数的所有和必需的参数
I am using reflection
to get all and required parameters of a function
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
当我得到一个默认值在需要之前的答案时,这是否是反射函数为所需参数返回错误计数的原因?
As i get in one answer that defaults comes before required, is this the reason the reflection function is returning wrong count for required parameters?
谢谢
推荐答案
'Optional' arguments 只是带有默认值的参数,该值是否为 null
, false
, 字符串(等)无关紧要 - 如果函数参数具有默认值,则它是可选的.
'Optional' arguments are just arguments with a default value, whether that value is null
, false
, a string (etc.) does not matter - if a function argument has a default value it is optional.
但是,在必需参数之前放置一个可选参数是没有意义的,因为您必须为前面的参数赋予一些值(即使它是 null
)才能到达' 必需的参数 - 所以最后一个 'required' 参数之前的所有参数都是有效的.
However, it wouldn't make sense to have an optional parameter come before a required parameter, as you must give the prior arguments some value (even if it's null
) in order to 'get to' the required argument - so all arguments before the last 'required' argument are effectively required.
一些例子:
// 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'
更新 RE:反思
如上所述,将可选"参数放在必需参数之前有效地使可选"参数成为必需,因为必须为其指定值才能满足方法签名.
As noted above, putting an 'optional' parameter before a required parameter effectively makes that 'optional' parameter required, as a value must be given for it in order to ever satisfy the method signature.
例如,如果第一个参数有默认值而第二个参数没有(如上面的 bad
函数),我们需要传递第二个参数,因此我们需要传递第一个参数也有论点,所以两者都是必需的".如果后续参数有默认值,仍然只需要前2个参数.
For example, if the first argument has a default and second argument does not (like in the bad
function above), we NEED to pass a second argument, and so we NEED to pass a first argument also, so both are 'required'. If there are subsequent arguments with default values, still only the first 2 arguments are required.
这篇关于php函数的必选参数混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!