I want this solution to be on SO when I started using PHP 2.5 years ago. It works great in the examples I created, and I don't understand why it should not be fully extensible. It offers the following advantages over those previously offered:
(i) all access to the parameters inside the function is carried out using named variables, as if the parameters were fully declared, and did not require access to the array
(ii) adapt existing functions very quickly and easily
(iii) for any function, only one line of additional code is required (in addition to the inevitable need to define your default parameters, which you will do in the function signature in any case, but instead you define them in an array). The credit for the additional line is fully connected with Bill Carvin. This line is identical for each function.
Method
Define your function with its required parameters and optional array
Declare your optional parameters as local variables
The crux: replace the previously declared default value of any optional parameters using the ones you passed through the array.
extract(array_merge($arrDefaults, array_intersect_key($arrOptionalParams, $arrDefaults)));
Call a function, pass its required parameters, and only those additional parameters that you need
For example,
function test_params($a, $b, $arrOptionalParams = array()) { $arrDefaults = array('c' => 'sat', 'd' => 'mat'); extract(array_merge($arrDefaults, array_intersect_key($arrOptionalParams, $arrDefaults))); echo "$a $b $c on the $d"; }
and then call it like this
test_params('The', 'dog', array('c' => 'stood', 'd' => 'donkey')); test_params('The', 'cat', array('d' => 'donkey')); test_params('A', 'dog', array('c' => 'stood'));
Results:
The dog stood on a donkey
Cat sitting on a donkey
There was a dog on the rug