0

Possible Duplicate:
Is it possible to skip parameters that have default values in a php(5) function call?

Lets say this is my function :

function myFunc($a ,$b = 'ball',$c = 'cat')
{
   echo "$a $b $c" ;
}



 myFunc("apple");   // output :  "apple ball cat"
 myFunc("apple","box"); // output : "apple box cat"

How can I call myFunc with default parameter for $b, eg

myFunc("apple", SOMETHING_HERE , "cow" ); // output : "apple ball cow"
Community
  • 1
  • 1
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175

2 Answers2

1

You can't do that by setting the default values in the prototype of the function :

function myFunc($a ,$b = 'ball',$c)
{
   echo "$a $b $c" ;
}

But there is a workaround :

function myFunc($a ,$b = null,$c = null)
{
   if ($b === null)
      $b = 'ball';
   if ($c === null)
      $c = 'cat';

   echo "$a $b $c" ;
}
Romain Guidoux
  • 2,943
  • 4
  • 28
  • 48
0

You can do it with func_get_args function and some special indication that a default value should be used (for example, pass NULL):

function myFunc() {
 $params = func_get_args();
 $defaults = array('apple', 'ball', 'cow'); //your default values
 foreach ($params as &key => &$value) {
   if ($value === NULL) $value = $defaults[$key];
 }

myFunc('apple', NULL, 'cow');

Having said that, I think it's not the best practice to do things like that. You should look into your function design once again - maybe you just need to refactor something slightly so it would be more intuitive.

Aurimas
  • 2,518
  • 18
  • 23