Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass specific variable in PHP function

I have a PHP function that requires can take 3 parameteres... I want to pass it a value for the 1st and 3rd parameters but I want the 2nd one to default...

How can I specify which ones I am passing, otherwise its interpreted as me passing values for the 1st and 2nd slots.

Thanks.

like image 537
Ian Storm Taylor Avatar asked Mar 18 '10 21:03

Ian Storm Taylor


1 Answers

You cannot "not pass" a parameter that's not at the end of the parameters list :

  • if you want to specify the 3rd parameter, you have to pass the 1st and 2nd ones
  • if you want to specify the 2nd parameter, you have to pass the 1st one -- but the 3rd can be left out, if optionnal.

In your case, you have to pass a value for the 2nd parameter -- the default one, ideally ; which, yes, requires your to know that default value.


A possible alternative would be not have your function take 3 parameters, but only one, an array :

function my_function(array $params = array()) {
    // if set, use $params['first']
    // if set, use $params['third']
    // ...
}

And call that function like this :

my_function(array(
    'first' => 'plop',
    'third' => 'glop'
));

This would allow you to :

  • accept any number of parameters
  • all of which could be optionnal

But :

  • your code would be less easy to understand, and the documentation would be less useful : no named parameters
  • your IDE would not be able to give you hints on which parameters the function accepts
like image 135
Pascal MARTIN Avatar answered Oct 18 '22 10:10

Pascal MARTIN