I have a function which takes two arguments but I want the second one to be optional:
function myFunction($arg1, $arg2) {
//blah
//blah
if (isset($arg2)) {
//blah
} else {
//blah
}
}
So when I call it, I might do myFunction("something")
or I might do myFunction("something", "something else")
.
When I only include one argument, PHP gives this warning:
Warning: Missing argument 2 for myFunction(), ...
So it works, but obviously the developers frown upon it.
Is it ok to do this or should I be passing in ""
or false
or 0
to the second argument when I don't want to use it and testing for that instead of using 开发者_如何学Cisset()
?
I've noticed that a lot of people miss out arguments when calling functions in JavaScript which is why I'm asking if it's done in PHP too.
Its done by setting up some parameters as optional/giving it a default:
function myFunction($arg1, $arg2 = false)
then you can call the function like this:
myFunction('something');
or
myFunction('something', 'something else');
You can set it in your function declaration:
function myFunction($arg1, $arg2 = NULL) {
This way, the second parameter is optional. Note that the optional parameters have to be at the end, you cannot have any non-optional parameters after them.
You need to set a default for the argument in the function declaration, like this:
function myFunction($arg1, $arg2 = false) {
//blah
//blah
if (isset($arg2)) {
//blah
} else {
//blah
}
}
function myFunction($arg1, $arg2=null)
http://www.php.net/manual/en/functions.arguments.php#functions.arguments.default
Define a default value of the parameter in the function:
public function foo($arg1, $arg2 = 'default') {
//yourfunction
}
精彩评论