Reputation: 21489
I have php function
by multi parameter. I want to call this function
with setting only last argument. Simple way is setting other argument empty. But it isn't good.
Is any way to call this function
with setting last argument and without setting other argument?
See this example:
function MyFunction($A, $B, $C, $D, $E, $F)
{
//// Do something
}
//// Simple way
MyFunction("", "", "", "", "", "Value");
//// My example
MyFunction(argument6: "Value")
Upvotes: 1
Views: 208
Reputation: 1229
Use an array as parameter and use type hinting and empty array as default value in function definition. Provide default values inside the function and override them by user values.
function MyFunction(array $args = []) {
// Provide default values
$defaults = [
'A' => 0,
'B' => 0,
'C' => 0,
'D' => 0,
'E' => 0,
'F' => 0
];
foreach ($defaults as $key => $val) {
if (!array_key_exists($key, $args)) {
$args[$key] = $val;
}
}
echo '<pre>';
print_r($args);
echo '</pre>';
}
MyFunction();
MyFunction(['F' => 77]);
Upvotes: 0
Reputation: 711
My suggestion is use array instead of using number of argument, For example your function call should be like this.
$params[6] = 'value';
MyFunction($params);
For identify that sixth parameter has set
function MyFunction($params){
If ( isset($params[6]) ) // parameter six has value
}
I hope that it will be a alternate way
Upvotes: 1
Reputation: 820
In the context of the question, this works. You can use each array key as a variable like $A, $B, ... But you have to be careful not to post $args with the old values you have previously set.
<?php
$args = array('A'=>'', 'B'=>'', 'C'=>'', 'D'=>'', 'E'=>'', 'F'=>'');
function MyFunction($args)
{
foreach($args as $key => $value)
$$key = $value;
echo $F;
//// Do something
}
$args['F'] = 'Value';
Myfunction($args);
Upvotes: 1