在PHP [名称]中按名称指定参数

I have no idea what this is called, but I've seen PHP supports a cool parameter passing like:

function myFunc($required_value, $optional_value1 = 'default', $optional_value2 = 'default2'){

}

And then I'd be able to do:

myFunc('something', $optional_value2 = 'test');

So 2 questions in regards to this:

  1. What is this technique called (for future references)?
  2. Since what PHP version is it supported?
</div>

The only think that comes to my mind is to pass arguments via array.

function f($params)
{ 
    if(!isset($params['name']) || !isset($params['adress'])) 
    {
        //trigger error throw exception or whatever
    }
    //do something with params
} 

and calling

f(array('name' => 'asdfasdf', 'adress' => 'adfasdf')); 

then in function you can check if there are enough params to process function.

PHP doesn't have named params like for example C#.

PHP support default values of parameters so you can use it for example:

 function f($name = "John Doe"){echo $name;}

when you call

echo f(); // John Doe will be displayed
echo f("Robert"); //Robert will be displayed

Am not sure what you are able to do but php does not support Named Parameters yet

Ruining

myFunc('something', $optional_value2 = 'test');

Does not mean $optional_value2 would become 'test` in the function See Demo

What you are currently implementing is called Default parameters in functions

its called default parameters.

In your exapmple. there is a slight mistake. given your function

function myFunc($required_value, $optional_value1 = 'default', $optional_value2 = 'default2'){
.....
}

you can call this in the following ways:

myFunc('required_value'); //$optional_value1 = 'default', $optional_value2 = 'default2'
myFunc('required_value', 'opt1'); //$optional_value2 = 'default2'
myFunc('required_value', 'opt1', 'op2');

thing to note is that php doesn't support named parameters, so there order is important. therefore, you can't omit middle params. so the following statements would be wrong because you are trying to use named parameters.

myFunc('something', $optional_value2 = 'test');

For more details, see this

this is Default Arguments

Important thing to note is that Optional parameters can only be specified in the last , so Required parameters come before the Optional parameters in the function definition e.g.

function myFunc($param1,$optional1= 'string',$optional2= 5) {

}

while calling the function we can call it as

myFunc($param1);
myFunc($param1 , 'new string');
myFunc($param1,'string',10);

but not myFunc($param1,10); skipping the middle argument is not allowed!!! The method you have used to call the func is wrong

In your example. there is a slight mistake. you can't omit middle params. so the following function call

   myFunc('something', $optional_value2 = 'test'); 

is not allowed! Further $optional_value2 = 'test' cannot appear in the function call...simply 'test' should be passed as an argument to the function.