Thursday, January 27, 2011

How do you create optional arguments in php?

In the php manual they describe functions like so:

string date ( string $format [, int $timestamp ] )

How would this function look when you define it?

  • function dosomething($var1, $var2, $var3='somevalue'){
    ..
    }
    
  • Give the optional argument a default value.

    function date ($format, $timestamp='') {
    }
    
    From mk
  • Some notes that I also found useful:

    • Keep your default values on the right side.

      function whatever($var1, $var2, $var3="constant", $var4="another")

    • The default value of the argument must be a constant expression. It can't be a variable or a function call.

    From ghostz00
  • The default value of the argument must be a constant expression. It can't be a variable or a function call.

    If you need this functionality however:

    function foo($foo, $bar = false)
    {
        if(!$bar)
        {
            $bar = $foo;
        }
    }
    

    Assuming $bar isn't expected to be a boolean of course.

    From Ross

0 comments:

Post a Comment