Optional parameters in PHP function without considering order

Viewed 3765

Is there a way in PHP to use a function which has optional parameters in its declaration where I do not have to pass an optional arguments which already have values declared and just pass the next argument(s) which have different values that are further down the parameter list.

Assuming I have a function that has 4 arguments, 2 mandatory, 2 optional. I don't want to use null values for the optional arguments. In usage, there are cases where I want to use the function and the value of the 3rd argument is the same as the default value but the value of the 4th argument is different.

I am looking for a not so verbose solution that allows me to just pass the argument that differs from the default value without considering the order in the function declaration.

  createUrl($host, $path, $protocol='http', $port = 80) {
    //doSomething
    return $protocol.'://'.$host.':'.$port.'/'.$path;
  }

I find myself repeating declaring variables so that I could use a function i.e to use $port, I redeclare $protocol with the default value outside the function scope i.e

$protocol = "http";
$port = 8080;

Is there any way to pass the 2nd optional parameter($port) without passing $protocol and it would "automatically" fill in the default value of $protocol i.e

 getHttpUrl($server, $path, $port);

This is possible in some languages like Dart in the form of Named Optional parameters.See usage in this SO thread. Is their a similar solution in PHP

8 Answers

PHP doesn't allow at this state to call functions parameters in the order we want.Maybe in the future it will.However you can easily achieve your purpose by using an associative array as the only argument, and then define, the default parameter in the function.For the call you will need to pass an array with only the values which interest you.This array will be merged with the default array.You can even implement required parameters and call them in any order you want. example:

    function mysweetcode($argument){
    $required=['first'];//specify required parameters here
    $default=['first'=>0,'second'=>1,'third'=>2];//define all parameters with their default values here
    $missing=[];
    if(!is_array($argument)) return false;
    $argument=array_intersect_key($argument,$default);
    foreach($required as $k=>$v){//check for missing required parameters
        if(!isset($argument[$v]))
            $missing[]=$v;
    }
    if(!empty($missing)){// if required are missing trigger or throw error according to the PHP version 
        $cm=count($missing);
        if (version_compare(PHP_VERSION, '7.0.0') < 0) {
            trigger_error(call_user_func_array('sprintf',
            array_merge(array('Required '.(($cm>1)?'parameters:':'parameter:').
            str_repeat('%s,',$cm).(($cm>1)?' are':' is').' missing'),$missing)),
            E_USER_ERROR);
        }else{
            throw new Error(call_user_func_array('sprintf',array_merge(
            array('Required '.(($cm>1)?'parameters:':'parameter:').
            str_repeat('%s',$cm).(($cm>1)?' are':' is').' missing'),$missing)));
        }
    }
    $default=array_merge($default,$argument);//assign given values to parameters
    extract($default);/*extract the parameters to allow further checking    
    and other operations in the function or method*/
    unset($required,$missing,$argument,$default,$k,$v);//gain some space 

    //then you can use $first,$second,$third in your code

    return $first+$second+$third;

}  

var_dump(mysweetcode(['first'=>9,'third'=>8]));//the output is 18

var_dump(mysweetcode(['third'=>8]));//this throws Error on PHP7 and trigger fatal error on PHP5 

You can check a live working code here

Well, this should work:

function myFunc($arg1, $arg2, $arg3=null, $arg4= null){
  if ( is_null( $arg3 ) && is_null( $arg4 ) {
    $arg3 = 3;
    $arg4 = 4;
  } else if ( is_null( $arg4 ) ) {
    $arg4 = $arg3;
    $arg3 = 3;
  }
    echo $arg1 + $arg2 + $arg3 + $arg4;
}

However I suggest you to rethink your problem (as a whole) because this is not a very good idea.

You could refactor this to use a parameter object; this way, you could include the default parameters in this object and set them in any order (with a trade-off of more verbose code). As an example using your above code,

<?php

class AdditionParameters
{
    private $arg1 = 0;
    private $arg2 = 0;
    private $arg3 = 3;
    private $arg4 = 4;

    public function getArg1() { return $this->arg1; }
    public function getArg2() { return $this->arg2; }
    public function getArg3() { return $this->arg3; }
    public function getArg4() { return $this->arg4; }

    public function setArg1($value) { $this->arg1 = $value; return $this; }
    public function setArg2($value) { $this->arg2 = $value; return $this; }
    public function setArg3($value) { $this->arg3 = $value; return $this; }
    public function setArg4($value) { $this->arg4 = $value; return $this; }
}

From there, you could simply call the function while passing in this new object.

function myFunc(AdditionParameters $request) {
    return $request->getArg1()
        + $request->getArg2()
        + $request->getArg3()
        + $request->getArg4();
}

echo myFunc((new AdditionParameters)->setArg1(1)->setArg2(2)->setArg4(6));
// or echo myFunc((new AdditionParameters)->setArg1(1)->setArg4(6)->setArg2(2));

Otherwise, PHP doesn't allow you to have named optional parameters. (e.g. myFunc(1, 2, DEFAULT, 4);)

You have the response in your question, you can declare your function like

function myFunc($arg1, $arg2, $arg3 = null, $arg4 = null){
    //here you check if the $arg3 and $arg4 are null
}

then you call your function using

myFunc($arg1, $arg2);

There is no such way in PHP(like in python for example).

You have to use some tricks in order to do that but will not always work. For example:

// creates instances of a class with $properties.
// if $times is bigger than 1 an array of instances will be returned instead.(this is just an example function)
function getInstance($class, $properties = [], $times = 1){
    //my code
}

$user = getInstance("User", ["name" => "John"]); // get one instance
$users = getInstance("User", ["name" => "John"],2); // get two instances.

If you want to use the function without passing the $parameters argument, like this:

$users = getInstance("User",2);

you can change the function to:

// creates instances of a class with $properties.
// if times is bigger than 1 an array of instances will be returned instead.
function getInstance($class, $properties = [], $times = 1){
    if(is_numberic($properties)){
        $times = $properties;
        $properties = [];
    }
    //my code
}

Of course, this strategy will work only if you parameters have different types.

PS. This method is use in the Laravel Framework a lot. From there I got the inspiration.

This is modified from one of the answers and allows arguments to be added in any order using associative arrays for the optional arguments

 function createUrl($host, $path, $argument = []){
   $optionalArgs = [
    'protocol'=>'http',
    'port'=>80];
  if( !is_array ($argument) ) return false;
  $argument = array_intersect_key($argument,$optionalArgs);
  $optionalArgs = array_merge($optionalArgs,$argument);
  extract($optionalArgs);
  return $protocol.'://'.$host.':'.$port.'/'.$path;
 } 



  //No arguments with function call
  echo createUrl ("www.example.com",'no-arguments'); 
  // returns http://www.example.com:80/no-arguments

  $argList=['port'=>9000];
  //using port argument only
  echo createUrl ("www.example.com",'one-args', $argList); 
  //returns http://www.example.com:9000/one-args

  //Use of both parameters as arguments. Order does not matter
  $argList2 = ['port'=>8080,'protocol'=>'ftp'];
  echo createUrl ("www.example.com",'two-args-no-order', $argList2); 
  //returns ftp://www.example.com:8080/two-args-no-order

As of version 8.0, PHP now has named arguments. If you name the arguments when calling the function, you can pass them in any order and you can skip earlier default values without having to explicitly pass a value for them.

For example:

function createUrl($host, $path, $protocol = 'http', $port = 80)
{
    return "$protocol://$host:$port/$path";
}

createUrl(host: 'example.com', path: 'foo/bar', port: 8080);

// returns: "http://example.com:8080/foo/bar"
Related