Default function arguments in dynamic languages

Dynamic programming languages in general and PHP in particular allow specifying default values for parameters of functions and methods.

The values can be specified directly in parameter list:

function example($foo = 5, $bar = 'test') {
    // ...
}

But if programmer needs to skip a parameter (that’s what default values are for), then he is forced to recall what is exact default value for skipped parameter, or open documentation for the specific function. This is not enough usable in practice.

Therefore we can act in a different way: as a formal default values always use null value, while initializing real default values inside function:

function example($foo = null, $bar = null) {
    if (null === $foo) {
        $foo = 5;
    }
    if (null === $bar) {
        $bar = 'test';
    }
    // ...
}

In this case, to skip any optional parameter, it will be enough just to specify the unified null value as its value:

example(null, 'qwerty');

In cases when parameter list gets too long, it makes sense to consider using named parameters as elements of associative array which is the only (or the last of two or three required or most often used) formal parameter of function:

function example($options) {
    $foo = array_key_exists('foo', $options)
         ? $options['foo']
         : 5;

    $bar = array_key_exists('bar', $options)
         ? $options['bar']
         : 'test';

    // ...
}