Question

Possible Duplicate:
php function overloading

I want to redeclare function such like this:

class Name{
    function a(){ something; }
    function a($param1){ something; }
}

but it returns

Fatal error: Cannot redeclare Name::a()

In java it just works. How can I do this in PHP?

Était-ce utile?

La solution

Use default parameters:

class Name{
    function a($param1=null){ something; }
}

If no parameter is passed to Name::a() it will assign a $param1 has a value of null. So basically passing that parameter becomes optional. If you need to know if it has a value or not you can do a simple check:

if (!is_null($param1))
{
 //do something
}

Autres conseils

You won't redeclare a function. Instead you can make an argument optional by assigning a default value to it. Like this:

function a($param1 = null){ something; }

Function arguments to not uniquely identify a function. In Java the arguments are strictly defined. This allows the compiler to know which function you are calling.

But, in PHP this is not the case.

function a()
{
    $args = func_get_args();
    foreach($args as $value)
    {
        echo $value;
    }
}

It's possible to create function that has no arguments define, but still pass it arguments.

a("hello","world")

would output

hello world

As a result, PHP can't tell the different between a() and a($arg). Therefore, a() is already defined.

PHP programmers have different practices to handle this single function problem.

You can define an argument with default values.

a($arg = 'hello world');

You can pass mixed variable types.

 function a($mixed)
 {
     if(is_bool($mixed))
     {
         .....
     }
     if(is_string($mixed))
     {
         .....
     }
 }

My preference is to use arrays with defaults. It's a lot more flexible.

 function a($options=array())
 {
       $default = array('setting'=>true);
       $options = array_merge($default,$options);
       ....
 }

 a(array('setting'=>false);

Unfortunately PHP does not support Method overloading like Java does. Have a look at this here for a solution: PHP function overloading
so func_get_args() is the way to go:

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top