Function overloading in php
Is function overloading possible in php.If yes, then how and if not then why?
Thanks in advance.
I have checked the php开发者_运维百科 manual which gives solution to overloading as mail() function can be overloaded by mb_mail() function .
But is this the proper way for overloading
No. Because it has not been implemented. There's a PECL extension that allows you to do this, but it makes your code not portable to environments where this extension is not available.
Don't ask why it has not been implemented.
Since PHP 5.3 you can use namespaces for 'kind of' overloading
namespace MyNamespace;
function mail() {
return \mail();
}
This can only be done internally (through a PHP extension), unless you install the PECL runkit extension, which exposes function overloading functionality to userspace.
However, you probably don't want to use runkit in a production environment, so there's no good way to do this from userspace.
i'm new to php .. so dont know about these extensions mentions above .. but recently i saw a method to overload function in php (sort of) ..
traditional function overloading is not supported in php because you can not have multiple functions with same name in php .. but you can use one single function which can take multiple arguments .. known as Variadic Function (http://en.wikipedia.org/wiki/Variadic_function)
function show()
{
$data = "";
$arr = func_get_args(); //Returns an Array of arguments passed
for($a = 0 ; $a < func_num_args() ; $a++ ) // func_num_args returns number of arguments passed .. you can also use count($arr) here
{
$data .= $arr[$a];
}
echo $data, "<br>";
}
show("Hey","Hii","Hello");
show("How Are You");
here .. i have passed variable arguments to a function and appended each of them in a string ..
ofcourse including a string is not necessary .. you can simply echo $arr array contents inside a loop .. hope that helps .. !!
精彩评论