William William - 29 days ago 15
PHP Question

How to inform only the first and the last arguments of a function?

How may I use this

function
and inform only the first and the last
arguments
?

Function

function foo($first = false, $second = false, $third = false, $last = false)
{
if($first && $last)
{
echo 'ok';
}
}


I've tried the code below, but it didn't work...

foo($first = true, $last = true);

Answer

PHP doesn't do named arguments as python does. See this question for more info.

However, life can be made easier by using other techniques like...

Modify the signature of the function to accept arguments as an associative array

Function

function foo($parameters)
{
  // Provide default values if parameters are not specified
  $first = isset($parameters['first']) ? $parameters['first'] : false;
  $second = isset($parameters['second']) ? $parameters['second'] : false;
  $third = isset($parameters['third']) ? $parameters['third'] : false;
  $last = isset($parameters['last']) ? $parameters['last'] : false;

  if($first && $last)
  {
    echo 'ok';
  }
}

Call

foo(['first' => true, 'last' => true]);

This way is suitable when you have a number of parameters big and variative enough and you have a complex logic inside the function so that writing all this code pays off.

It is not very convenient, however, because the default values are specified not in an obvious way, there's extra code and it's hard to track parameter usages.

Modify the signature of the function to accept a parameter object which holds all the necessary info

This is the way to go for complex signatures and especially if you have a cascade of methods which use the same arguments. I love it because it solved a big problem with passing up to 10 query parameters through processing pipeline. Now it's just one object with possibility to find every parameter usage and friendly autosuggestion of available parameters when typing ->.

Parameter object class

class ParameterObject
{
    public $first = false;
    public $second = false;
    public $third = false;
    public $last = false;
}

Function

function foo(ParameterObject $paramObj)
{
  if($paramObj->first && $paramObj->last)
  {
    echo 'ok';
  }
}

Call

$paramObj = new ParameterObject();
$paramObj->first = true;
$paramObj->last = true;

foo($paramObj);

Note! You can modify the object to use method for setting parameters which will provide you with possibility of chaining if you return $this in every set method. So the function call would like like this:

$paramObj = new ParameterObject();
foo($paramObj->setFirst(true)->setSecond(true));