2

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?

Community
  • 1
  • 1
Maximus
  • 471
  • 1
  • 10
  • 25

4 Answers4

6

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
}
John Conde
  • 217,595
  • 99
  • 455
  • 496
4

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; }
datasage
  • 19,153
  • 2
  • 48
  • 54
2

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);
Reactgular
  • 52,335
  • 19
  • 158
  • 208
1

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:

Community
  • 1
  • 1
Stefan
  • 2,164
  • 1
  • 23
  • 40