I am looking for the exact type of a Required Parameter in a PHP Function signature
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?
UPDATE
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?
Thanks
‘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.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.Some examples:
Update RE: Reflection
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.
For example, if the first argument has a default and second argument does not (like in the
badfunction 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.