Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parameters aren't truly optional

Tags:

php

I would like to have real optional parameters in PHP. I realize that I can do something like this:

function my_function($req_var, $opt_var1 = 90, $opt_var2 = "lala") {
    die("WEEEEEEEE!");
}

However, if I want to only specify the value of $opt_var2, I still must specify a value for $opt_var1.

Here's an example.

my_function("lala", 90, "omg");

In other words, I have to explicitly write 90 as $opt_var1 even though it's only $opt_var2 that I want to change.

Is it possible to do something like this?

my_function("lala", default, "omg");

That would be so helpful.

like image 950
Mathias Lykkegaard Lorenzen Avatar asked Dec 08 '25 10:12

Mathias Lykkegaard Lorenzen


1 Answers

function my_function($req_var, $opt_var1 = NULL, $opt_var2 = NULL) {
    if ($opt_var1 === NULL) {
        $opt_var1 = 90;
    }
    if ($opt_var2 === NULL) {
        $opt_var2 = "lala"
    }
}
my_function("lala", NULL, "omg");
like image 94
Your Common Sense Avatar answered Dec 10 '25 00:12

Your Common Sense