开发者

How do you pass your (optional) arguments to a user-defined-function?

I mean, how do you pass your arguments to a function?

Do your user function call looks like this:

$this->getSomeNumber($firstArg, $secondArg, null);

or do you detect how many arguments was passed to the function and then do the job?

I wonder if is there any coding style covering this. And how do other programming languages handle this?

UPDATE

Example fot those, who not understand:

function doSmth($firstArgument) {
    if(func_num_args() > 1) {
        //d开发者_开发技巧o job if second argument was passed
    }
}

Second example:

function doSmthElse($firstArgument, $secondArgument) {
    if($secondArgument) {
        //do job if second argument was passed
    }
}

And then you call it like:

doSmth($var, $secondvar) or doSmth($var)

//**OR**

doSmthElse($var, $secondvar) or doSmthElse($var, null)

Which is better to use? I mean which do other programmers expect from you?


If the argument is optional, specify it normally with a default value:

function foo($requiredArg, $optionalArg = null)

If the function takes multiple optional arguments, specify them explicitly like in the above example.

If the function takes a variable number of arguments (for example, such as sprintf), then use func_get_args & co.

/**
 * Specify here as a comment that this function takes a variable amount of args
 */
function doSomethingWithParameters() {
    ...
}

If the function takes required parameters and a variable amount of parameters, the same approach applies: Specify always required parameters explicitly like in the first example.

Using comments to clarify variable args etc. is always a good idea. It might be an even better idea to use an array instead, but this would probably depend on what you're doing.


You want dollar signs before those args:

$this->getSomeNumber($firstArg, $secondArg, null);

But if you're really asking about how to use variable numbers of arguments in php, see func_num_args and func_get_args in the help.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜