Reputation: 48758
Excuse my newbishness. While working on an ASP.Net based website, I remember seeing some methods in which could accept a different number of arguments. Specifically, they would do different things, depending on the number of parameters passed to them.
For example:
Email.sendEmail(address,subject,body);
would do something different to:
Email.sendEmail(address,bccaddresses,subject,body);
Is it possible for methods in PHP to do something similar? What is this thing called? Or have I just totally misremembered something?
Upvotes: 1
Views: 199
Reputation: 14446
You could use an associative array as the argument, and make use of extract().
function sendMail($opts){
extract($opts, EXTR_SKIP); // EXTR_SKIP prevents extract from overwriting anything already in the symbol table
if(isset($bccaddresses)){
// do something with the bcc addresses
}
echo "sending some mail to $to with subject $subject";
}
sendMail(array("to"=>"[email protected]", "subject"=>"Hi!"));
This lets you pass in the arguments as named values, with optional values as you see fit.
Upvotes: 2
Reputation: 96258
function sendEmail($address, $bccaddresses, $subject, $body=NULL) {
if ($body === NULL) {
$bccaddresses=""; //or whatever default you want
//shift arguments:
$subject = $bccaddresses; $body = $subject;
}
}
Upvotes: 3
Reputation: 14446
In PHP, you set default values for functions.
function myFunc($val1 = 1, $val2 = 2, $val3 = 3){
echo "$val1 $val2 $val3";
}
myFunc(); // outputs 1 2 3
myFunc(5); // outputs 5 2 3
myFunc(8, 1); // outputs 8 1 3
Upvotes: 1
Reputation: 17010
You are searching for func_num_args()
and func_get_args()
.
See also related examples, it shows you how to do exactly what you need.
Upvotes: 1