Reputation: 10067
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 isset()
?
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.
Upvotes: 2
Views: 745
Reputation: 29
Define a default value of the parameter in the function:
public function foo($arg1, $arg2 = 'default') {
//yourfunction
}
Upvotes: 0
Reputation: 37065
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
}
}
Upvotes: 1
Reputation: 4023
function myFunction($arg1, $arg2=null)
http://www.php.net/manual/en/functions.arguments.php#functions.arguments.default
Upvotes: 0
Reputation: 91734
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.
Upvotes: 3
Reputation: 12281
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');
Upvotes: 6