Named function parameters in PHP

Officially, PHP doesn’t support named function parameters. But there is one easy way to emulate this feature – so easy that it doesn’t really matter that this feature is missing. It’s actually a pretty old trick inspired from Javascript I’ve been using since forever. I thought everyone knew it, but I’m still surprised by how many people come up with overly complicated solutions. Anyway, imagine you have a method that have a lot of optional parameters. Without named parameters, it goes like this:

// $queue is required, the rest is optionnal
function bind_queue($queue, $durable = false, $auto_delete = true, $name = false, $answer = null)
{ 
...
}

Later in your code, if you want to specify another value for $answer, you have to copy the values of every intermediate parameters in your function call. It’s time consuming, error prone and confusing.

// Good luck remember which parameter is what. 
bind_queue($my_queue, false, true, false, 42);

So instead, it’s much better to use an associative array, like this:

// leave the required parameter part of the function definition, the options goes into an array
function bind_queue($queue, array $opt = array())
{
  // we define the default values, and merge with the user values at the same timle
  $opt = array_merge(array(
    'durable' => false,
    'auto_delete' => true,
    'name' => false,
    'answer' => null
  ), $opt);

  // use $opt['answer'] to access the 'answer' optionnal parameter
}

Later in your code, if you want to override answer, you can only write this:

bind_queue($my_queue, ['answer' => 42]);

Much easier to read, isn’t it?