0

Bit tricky question but this saves lot of time if you have to modify the script later on to add a third parameter which is a optional, while second was also optional and mostly it was used as second parameter not set, now when you add the third parameter you have to scan through everywhere to find the code snippet and add/set second and then add third ..

is there a easy way to do this ?

example :

  public static function result($sql, $i = 0, $r = 0) {
  //code
  } 

if we need to add the third $r, later on and most of the times if the code was used as

 result($sql);

now everywhere i had to scan and do

 result($sql,0,10);

is there a easy way to set the third parameter without setting the second one ?

mahen3d
  • 7,047
  • 13
  • 51
  • 103
  • 1
    No, there isn't. You have to provide the second parameter value. – xdazz Jun 28 '12 at 09:29
  • Related question: http://stackoverflow.com/questions/10881630/php-calling-functions-with-multiple-variables/ – Niko Jun 28 '12 at 09:31

2 Answers2

2

No this is not possible, however you may want to consider setting the optional parameters to be null, and then setting the default in the function.

For example:

public static function result($sql, $i = null, $r = null) {
   if(is_null($i)){
       $i="default";
   }
   ... etc
} 

This way, you can maintain the default in the function instead of having to duplicate it throughout your codebase.

Paul Bain
  • 4,364
  • 1
  • 16
  • 30
0

add an array of possible parameters

public static function result($sql, $settings=null) {
  if(is_array($settings) {
    if(isset($settings['i']) {
       // condition code
    }
    if(isset($settings['r']) {
      // condition code
    }
  }
  // normal code
} 
Waygood
  • 2,657
  • 2
  • 15
  • 16
  • 1
    I think the problem with using a "settings" array like this is that the function signature no longer describes it's function, you'd have to read the entire code to work out all valid arguements etc – Paul Bain Jun 28 '12 at 09:35