PHP Function with Optional Parameters

2019-01-10 08:03发布

I've written a PHP function that can accepts 10 parameters, but only 2 are required. Sometimes, I want to define the eighth parameter, but I don't want to type in empty strings for each of the parameters until I reach the eighth.

One idea I had was to pass an abstracted function with an array of parameters which passes it along to the real function.

Is there a better way to set up the function so I can pass in only the parameters I want?

11条回答
forever°为你锁心
2楼-- · 2019-01-10 08:34

If only two values are required to create the object with a valid state, you could simply remove all the other optional arguments and provide setters for them (unless you dont want them to changed at runtime). Then just instantiate the object with the two required arguments and set the others as needed through the setter.

Further reading

查看更多
We Are One
3楼-- · 2019-01-10 08:36

What I have done in this case is pass an array, where the key is the parameter name, and the value is the value.

$optional = array(
  "param" => $param1,
  "param2" => $param2
);

function func($required, $requiredTwo, $optional) {
  if(isset($optional["param2"])) {
    doWork();
  }
}
查看更多
Animai°情兽
4楼-- · 2019-01-10 08:36

If you are commonly just passing in the 8th value, you can reorder your parameters so it is first. You only need to specify parameters up until the last one you want to set.

If you are using different values, you have 2 options.

One would be to create a set of wrapper functions that take different parameters and set the defaults on the others. This is useful if you only use a few combinations, but can get very messy quickly.

The other option is to pass an array where the keys are the names of the parameters. You can then just check if there is a value in the array with a key, and if not use the default. But again, this can get messy and add a lot of extra code if you have a lot of parameters.

查看更多
ら.Afraid
5楼-- · 2019-01-10 08:39
func( "1", "2", default, default, default, default, default, "eight" );
查看更多
Rolldiameter
6楼-- · 2019-01-10 08:40

Make the function take one parameter: an array. Pass in the actual parameters as values in the array.


Edit: the link in Pekka's comment just about sums it up.

查看更多
登录 后发表回答