0

I have a function

public function test($arg1, $arg2 = "a", $arg3 = "b")

Is there a way to call it specifying only $arg1 and $arg3 leaving $arg2 with default value?

Poma
  • 8,174
  • 18
  • 82
  • 144
  • No, there isn't. To be able to pass `$arg3`, you must pass `$arg2` as well, but you could just pass `$arg2`'s default value? `test('hello', 'a', 'world');` – M. Eriksson Dec 22 '16 at 06:59
  • 1
    except some trickery with `func_get_args()` or using one named array as parameter? no. optional arguments *have* to be after the last mandatory argument. (maybe there's something in php7, but i'm not sure) – Franz Gleichmann Dec 22 '16 at 06:59
  • 1
    I would usually `test('hello', null, 'world!');` and that goes for other langs too... Maybe you can do a test to see if `$arg2` is null and based on this apply your "default" value. – Craig van Tonder Dec 22 '16 at 07:01
  • @MagnusEriksson Hit enter too soon, see updated... – Craig van Tonder Dec 22 '16 at 07:03

3 Answers3

2
function test($arg1, $arg2 = "a", $arg3 = "b") {
    if (is_null($arg2)) $arg2 = "a";
    return $arg1.' '.$arg2.' '.$arg3;
}

echo test(1, null, 3);

Output:

1 a 3

Will point out too that in JavaScript this is quite common:

function test (input, callback) {
  $.post( "example.com/endpoint", input, function(err, data) {
    if (error || response.statusCode !== 200) {
      callback(true, response)
    }
    callback(null, data)
  })
}

test({
  'id': 1,
  'name': 'Mary'
}, function (err, data) {
  if (err) {
    console.log.error('Error!!')
    console.log(data)
  }
  console.log.info(data)
})
Craig van Tonder
  • 7,497
  • 18
  • 64
  • 109
0

I think you are referring to using a anonymous function

How can I create a function dynamically?

Community
  • 1
  • 1
Cesar Bielich
  • 4,754
  • 9
  • 39
  • 81
  • I think the main idea with optional arguments is that there are situations when you _do_ want to use them in. If you _never_ will send the second argument, then your solution will make sense. – M. Eriksson Dec 22 '16 at 07:08
0

you can use currying function like this: refer this post

function foo($x, $y, $z) {
  echo "$x - $y - $z";
}

$bar = function($z) {
  foo('A', 'B', $z);
};

$bar('C');

also:

function foo($x, $y, $z) {
  echo "$x - $y - $z";
}

function fnFoo($x, $y) {
  return function($z) use($x,$y) {
    foo($x, $y, $z);
  };
}

$bar = fnFoo('A', 'B');
$bar('C');
Community
  • 1
  • 1
LF00
  • 27,015
  • 29
  • 156
  • 295