If your function/method signature has only one optional parameter, func_num_args()
or func_get_args()
can be checked with confidence inside the function body.
Code: (Demo)
function foo($a = null) {
echo json_encode(['func_num_args' => func_num_args(), 'func_get_args' => func_get_args()]);
echo "\n";
}
echo "no param: " , foo();
echo "a as null: " , foo(a: null);
Output:
no param: {"func_num_args":0,"func_get_args":[]}
a as null: {"func_num_args":1,"func_get_args":[null]}
Bear in mind that if you have multiple parameters in your function/method signature, func_
functions lack the necessary precision to express exactly which parameter was passed-in versus assigned by default value.
func_get_args()
produces an indexed array and func_num_args()
produces an integer -- neither which is not helpful. Because "named parameters" allow data to be passed-in in any order, there can be no way of knowing which optional parameter was omitted. The best that can be achieved is determining that either all optional parameters were passed-in or none were passed-in.
Code: (Demo):
function foo($a = null, $b = null, $c = null, $d = null) {
echo json_encode(['func_num_args' => func_num_args(), 'func_get_args' => func_get_args()]);
echo "\n";
}
echo "no params: " , foo();
echo "a as null: " , foo(a: null);
echo "b as null: " , foo(b: null);
echo "c as null: " , foo(c: null);
echo "d as null: " , foo(d: null);
echo "d & a as null: " , foo(d: null, a: null);
Output:
no params: {"func_num_args":0,"func_get_args":[]}
a as null: {"func_num_args":1,"func_get_args":[null]}
b as null: {"func_num_args":2,"func_get_args":[null,null]}
c as null: {"func_num_args":3,"func_get_args":[null,null,null]}
d as null: {"func_num_args":4,"func_get_args":[null,null,null,null]}
d & a as null: {"func_num_args":4,"func_get_args":[null,null,null,null]}
f(0)
should produce the same result, regardless of the "source" of the argument0
. – Sloe