faqts : Computers : Programming : Languages : PHP : kms : Functions

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

30 of 71 people (42%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

Can one do function overloading in PHP as in Java?

Mar 28th, 2007 12:02
Mark Boudreau, Nathan Wallace, Mark Peoples, Rasmus Lerdorf


Example:

function print_page($error1, $errormsg1)
{
        print("$error1 - $errormsg1");
}

function print_page($error1, $errormsg1,$error2, $errormsg2)
{
        print("$error1 - $errormsg1");
        print("<br>");
        print("$error2 - $errormsg2");
}

The proper function would be used depending on the arguments passed to
it...

Nope, but just do:

 function print_page($error1, $errormsg1, $error2=0, $errormsg2="")
 {
       print("$error1 - $errormsg1");
       if($error2 || $errormsg2) {
             print("<br>");
             print("$error2 - $errormsg2");
       }
 }

Seems cleaner to me.




You can also just not specify arguments, and take action based on what
is passed to the function.

function print_page() {
	$arguments = func_num_args();
	$arg_list = func_get_args();
	for($t=0;$t<$arguments; $t++ ) {
		if ($t%2 != 0){
			print("<br/>" . $arg_list[$t-1] . " - " . $arglist[$t]);
		}
	}
}