Reputation: 15886
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.
Upvotes: 3
Views: 87
Reputation: 5868
You can use a parameter that is an associative array and extract
it:
function func($options= array()) {
$option1= "default value";
..
extract($options);
..
}
Upvotes: 2
Reputation: 12168
There is a way with array parameters:
function my_func(array $params = array()){
$arg1 = isset($params['one']) ? $params['one'] : 'default';
$arg2 = isset($params['two']) ? $params['two'] : 'default';
$arg3 = isset($params['three']) ? $params['three'] : 'default';
// ...
}
Upvotes: 3
Reputation: 157839
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");
Upvotes: 6