0

If I have the following function:

function foo($a = 'a', $b = 'b', $c = 'c', $d = 'd')
{
    // Do something
}

Can I call this function and only pass the value for $d, therefore leaving all the other arguments with their defaults? With code something like this:

foo('bar');

Or do I have to call it with something like this:

foo(null, null, null, 'bar');
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
freshest
  • 6,229
  • 9
  • 35
  • 38

6 Answers6

1

You have to use nulls like you said:

foo(null, null, null, 'bar');

If you don't mind creating more functions you could do something like this, I'd imagine the overall code would be neater.

function update_d($val){
    foo(null, null, null, $val);
}

Or you could use arrays like so:

$args = array($a = 'a', $b = 'b', $c = 'c', $d = 'd');
foo($args);
472084
  • 17,666
  • 10
  • 63
  • 81
1

No, you cannot. Use arrays:

function foo($args) {
   extract($args);
   echo $bar + $baz;
}

foo(array("bar" => 123, "baz" => 456));

Write a bug report on php.net and ask them to add named arguments to the language!

user187291
  • 53,363
  • 19
  • 95
  • 127
  • Please don't write a bug report on php.net asking for named arguments as several have been written over the years, so any new bug would be a duplicate. There has been lots of discussion on the topic between the developers (even recently) with no decision to add this feature to PHP. However, do feel free to draft an [RFC](https://wiki.php.net/rfc) on the subject and discuss it (again) on the [PHP internals mailing list](http://php.net/mailing-lists.php). – salathe Sep 30 '11 at 16:12
  • absolutely true, unfortunately. – salathe Oct 01 '11 at 10:04
0

You have to do it like

foo(null, null, null, 'bar');

An alternative is to leave the arguments out of the function signature, and use func_get_args() to retrieve the values;

function foo() {
    $args = func_get_args();

But then still, if you would leave out the first three null values, there's no way to know that 'bar' is the $d parameter. Note by the way that this approach is undesirable most of the times, because it obfuscates your function signature and hurts performance.

Rijk
  • 11,032
  • 3
  • 30
  • 45
0

Short answer: No. Long answer: Nooooooooooooooooooooooooooooo.

Default argument value will be used when the variable is not set at all.

Yousf
  • 3,957
  • 3
  • 27
  • 37
0

You can't do it without overloading techniques.

In this case, your program assumes that if only one param is passed, it's the fourth.

corretge
  • 1,751
  • 11
  • 24
-1

func_get_args() - Gets an array of the function's argument list.
func_num_args() - Returns the number of arguments passed to the function

function foo()
{
     $numargs = func_num_args();
     echo "Number of arguments: $numargs<br />\n";
}


foo(a); foo(1,b,c); will work fine
xkeshav
  • 53,360
  • 44
  • 177
  • 245