1

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")
Mohammad
  • 21,175
  • 15
  • 55
  • 84

3 Answers3

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

kannan
  • 691
  • 5
  • 17
1

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);
sinaza
  • 820
  • 6
  • 19
  • It is unsafe to set local variables in this way. Imagine what happens if there are some keys passed like `args`, `key`, `value`, etc., like any of other local variables. Outer code should not suppose any details of the called function – Max Zuber Nov 29 '15 at 13:01
  • @MaxZuber You are absolutely right. I tried to state that it's not a safe way but sometimes people have to see something work for learning purposes. That was my main intention :) – sinaza Nov 29 '15 at 13:04
0

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]);
Max Zuber
  • 1,217
  • 10
  • 16