overloaded functions
Moderator: General Moderators
-
thegreatone2176
- Forum Contributor
- Posts: 102
- Joined: Sun Jul 11, 2004 1:27 pm
overloaded functions
Is there any plans to implement overloaded functions in php? In C++ it is very useful to be able to overload functions and have the differnet functions call based on how many pararments there is. for example in c++
int show()
{
cout << "hi";
}
int show(int a)
{
cout << a;
}
int main()
{
show();
show(1);
return 0;
}
It is a very useful thing to have avaiable and I am wondering why php has never implemented it. Is there some reason it cant be done or was there some former decision saying it wont be included?
int show()
{
cout << "hi";
}
int show(int a)
{
cout << a;
}
int main()
{
show();
show(1);
return 0;
}
It is a very useful thing to have avaiable and I am wondering why php has never implemented it. Is there some reason it cant be done or was there some former decision saying it wont be included?
-
Charles256
- DevNet Resident
- Posts: 1375
- Joined: Fri Sep 16, 2005 9:06 pm
well, it's easy to emulate using either func_get_args() or __call:
Code: Select all
// using your example
function show() {
if(!func_num_args()) {
echo "hi";
} else {
echo func_get_arg(0);
}
}
show();
show(1);- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
Re: overloaded functions
You can do the same thing in PHP like the example given or just:thegreatone2176 wrote:Is there any plans to implement overloaded functions in php? In C++ it is very useful to be able to overload functions and have the differnet functions call based on how many pararments there is. for example in c++
int show()
{
cout << "hi";
}
int show(int a)
{
cout << a;
}
int main()
{
show();
show(1);
return 0;
}
It is a very useful thing to have avaiable and I am wondering why php has never implemented it. Is there some reason it cant be done or was there some former decision saying it wont be included?
Code: Select all
function show($a='') {
if ($a == '') {
echo 'hi';
} else {
echo $a;
}
}
show();
show(1);Code: Select all
function show() {
if(func_num_args()) {
$a = func_get_arg(0);
if (is_array($a)) {
foreach ($a as $val) {
echo "$val<br/>";
}
} else {
echo $a;
}
} else {
echo "hi";
}
}
show();
show(1);
show(array('one','two','three'));-
thegreatone2176
- Forum Contributor
- Posts: 102
- Joined: Sun Jul 11, 2004 1:27 pm