2

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

1
  • 3
    What do you intend to accomplish using function overloading in PHP? Commented Aug 8, 2010 at 12:30

3 Answers 3

3

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();
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

In your opinion, how to implement function overloading
@Ankur Why do you need it for? Can't you just wrap the function in another one?
0

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 .. !!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.