I'm working on a simple class right now to get my head around OOP and I need some help with a function. The function receives various parameters, some of are optional:
public function Test($req, $alsoreq, $notreq = null, $notreq2 = null, $notreq3 = null)
{
...
}
How do I call the function, passing the two first parameters and the last one?
For example:
Test('req', 'alsoreq', 'notreq3');
Ignoring the notreq2 and notreq?
I tried
Test('req', 'alsoreq', '', '', 'notreq3');
but this seems ugly and hackish.
You can't. Think about it, if you could do that, how would PHP be able to tell if the third argument is supposed to be the $notreq, $notreq2 or $notreq3? A less hackish way would be:
Test($req, $alsoreq, NULL, NULL, $notreq3);
As you are making it clear that the first two optional args are NULL.
Choose the orders of arguments wisely, so the ones that get used more often come first.
Alternatively, you can use an array:
public function Test($req, $alsoreq, array $notreq) { ... }
// no optional args
Test($req, $alsoreq);
$optional = array('arg1' => 'something', 'arg2' => 'something else');
Test($req, $alsoreq, $optional);
$optional = array('arg3' => 'hello');
Test($req, $alsoreq, $optional);
There seem to be no way. As written in php manual:
Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.
You are trying to put non-default value (notreq3) on the right of default (notreq2, notreq1). Ugly and hackish way is likely to be more correct.
Regards, Serge
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With