问题
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")
回答1:
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
回答2:
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);
回答3:
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]);
来源:https://stackoverflow.com/questions/33981778/call-php-function