3

I am trying to build a function that has 2 default values, but on some occasions I need to supply only the first argument, and others only the second. Is there a way in PHP that I can do this, or is there a way of doing what I want that is considered standard?

Example

function ex($a, $b = null, $c = null) {
    ....
}

ex($a, $b, $c) // WORKS FINE

ex($a) // WORKS FINE

ex($a, $b) // WORKS FINE

ex($a, $c) // WANT VAR C TO BE VAR C IN THE FUNCTION AND NOT VAR B

Thanks

Griff
  • 1,647
  • 2
  • 17
  • 27
  • 2
    But how can the function tell whether `$c` is meant to be the second or the third argument? – Pekka Jun 03 '12 at 15:42
  • If you want keyword arguments instead of positional arguments I'd suggest you to switch to Python. Then you can do `ex(a, c=c)` – ThiefMaster Jun 03 '12 at 15:45

3 Answers3

5
ex($a, $c) // WANT VAR C TO BE VAR C IN THE FUNCTION AND NOT VAR B

Skip second param:

ex($a, null, $c);

Learn more on official docs

j0k
  • 22,600
  • 28
  • 79
  • 90
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
2

Just call it like this:

ex($a, null, $c);
Jeroen
  • 13,056
  • 4
  • 42
  • 63
1

You can use associated arrays

Consider the following code:

<?php

function tryThis($parms)
{
  $defaults = array(
      'a' => 5,
      'b' => null,
      'c' => 'Wibble' );
   $parms = array_merge($defaults, $parms);
   var_dump($parms);
}

// Use it as follows

tryThis(array('a'=>7, 'c'=>'Hello'));
tryThis(array('b'=>'Hi There'));

?>

It enables one to put the parameters into any order and allows for defaults of any paramteres. The only drawback is that you have to access the parameters through the associated array.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127