Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parameters in PHP function without considering order

Tags:

php

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

like image 781
Blacksmith Avatar asked Aug 28 '18 19:08

Blacksmith


1 Answers

You could potentially use a variadic function for this.

Example:

<?php

function myFunc(...$args){
    $sum = 0;
    foreach ($args as $arg) {
        $sum += $arg;
    }

    return $sum;
}

Documentation: http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list

like image 57
thecoolestguyever123 Avatar answered Nov 14 '22 22:11

thecoolestguyever123