开发者

How do I add optional arguments to my function? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

How do you create optional arguments in php?

I built a function with 1 argument. That function is called numerous places on many, many pages on my site. I just decided that I need another parameter for this function.

In order to avoid "Warning: Missing argument" errors, is there any way to add a second argument with a bit of logic that tests the presence of a second argument in the calling command?

I do not want to go back through my entire website and try to catc开发者_运维知识库h and update every function call merely to throw a null value on it in order to void the error messages.

Thanks.


You can specify a default value for your arguments:

function foo($arg1, $optional_arg2 = NULL)
{
  // ...
}

$optional_arg2 = NULL specifies that if not given when the function is called, $optional_arg2 will be NULL. The default value of an argument can be a scalar value (string, number or boolean), an array, or NULL, but it cannot be a variable, class member or function call.


You can define default the second argument value.

function functionName( $first, $second = false ) { ... }

And now if you left the second argument it will have false value. In the next case you call

functionName("test", true);

and overwrite default value.


//@params array $options

    function test($options) {
       $option1 = $options['option1'];
       ...
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜