Mr Chimp Learns to Write

if (!$geek) { header('Location:http://google.com'); }

Optional Arguments

with 11 comments

D’you wanna take this outside?

So you have a function in PHP. It has multiple arguments. In fact, it has multiple optional arguments. It might look something like this:

function options($a=1, $b=2, $c=3){
    echo $a . '-' . $b '-' . $c;
}

What happens when you want to specify a value for $c but leave $a and $b as their default values?

Short answer: You don’t.

Long answer: No, seriously, it can’t be done. The only way around it is to, instead of passing three variables, pass an array which contains the variables you want to use, then merge this with an array of default values. Or you could pass NULL and then test for it something like this: if ($a = NULL){ $a=1}.

Written by Mr Chimp

November 17th 2009 at 2:18 pm

Posted in Uncategorized

Tagged with , ,

11 Responses

Subscribe to comments with RSS.

  1. I was under the impression that you could do something like:

    function options($a=NULL, $b=NULL, $c=3){
    echo $a . ‘-’ . $b ‘-’ . $c;
    }

    I’m probably wrong though as I have little evidence to back it up.

    Dan

    November 17th 2009 at 4:25 pm

  2. You could do that but it wouldn’t solve the problem.

    Mr Chimp

    November 17th 2009 at 4:36 pm

  3. how about

    function options($a=1, $b=2, $c=3){
    if(typeof($a) == ‘array’) {
    $newa = $a['a'] or 1;
    $newb = $a['b'] or $b;
    $newc = $a['c'] or $c’
    }
    $a = $newa;
    $b = $newb;
    $c = $newc;
    echo $a . ‘-’ . $b ‘-’ . $c;
    }

    I’m not sure about the syntax, but you get the idea…

    Skilldrick

    November 17th 2009 at 6:05 pm

  4. Yeah, the ceejayoz one looks pretty good.

    Or is a bit like if not:

    Copying a bit from http://stackoverflow.com/questions/89154/benefits-of-using-short-circuit-evaluation/89313#89313

    open($filename) or die("couldn't open file");
    
    //is equivalent to:
    
    if(! open($filename) )
        die("couldn't open file");
    

    Skilldrick

    November 17th 2009 at 6:55 pm

    • So the idea is, if $a['a'] is undefined, it’ll be the falsy, and the ‘or’ statement will be execute… I haven’t tried this though :P

      Skilldrick

      November 17th 2009 at 6:56 pm

      • Ah, that’s pretty obvious, really! I’ve seen “or die” before, but never considered that you could use “or” on its own.

        Mr Chimp

        November 18th 2009 at 3:44 pm

      • Yeah, I came across that recently too. I think it’s short-circuit evaluation, like:

        if( funcThatReturnsTrue() || funcThatBlowsUpTheWorld() ) {
            //let's hope this works!
        }
        

        Because the first part of the conditional is true, PHP knows that the second part is irrelevant, so doesn’t evaluate it. Phew!

        Skilldrick

        November 19th 2009 at 10:49 am


Leave a Reply