Call PHP function

╄→尐↘猪︶ㄣ 提交于 2019-12-11 11:32:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!