Josh K
Josh K

Reputation: 28883

Same named function with multiple arguments in PHP

I started off OOP with Java, and now I'm getting pretty heavy into PHP. Is it possible to create multiples of a function with different arguments like in Java? Or will the interpreted / untyped nature of the language prevent this and cause conflicts?

Upvotes: 35

Views: 60923

Answers (10)

YOU
YOU

Reputation: 123841

Following isn't possible with php

function funcX($a){
    echo $a;
}
function funcX($a,$b){
    echo $a.$b;
}

Instead do this way

function funcX($a,$b=null){
    if ($b === null) {
       echo $a; // even though echoing 'null' will display nothing, I HATE to rely on that
    } else {
       echo $a.$b;
    }
}

funcX(1) will display 1, func(1,3) will display 13

Upvotes: 4

Don'tDownvoteMe
Don'tDownvoteMe

Reputation: 501

I have got 2 methods, getArrayWithoutKey which will output all the entries of an array without supplying any key value. The second method getArrayWithKey will output a particular entry from the same array using a key value. Which is why I have used method overloading there.

class abcClass
{
        private $Arr=array('abc'=>'ABC Variable', 'def'=>'Def Variable');


        public function setArr($key, $value)
        {
            $this->Arr[$key]=$value;
        }

        private function getArrWithKey($key)
        {
            return $this->Arr[$key];
        }
        private function getArrWithoutKey()
        {
            return $this->Arr;
        }

        //Method Overloading in PHP

        public function __call($method, $arguments)
        {
            if($method=='getArr')
            {
                    if(count($arguments)==0)
                    {
                                return $this->getArrWithoutKey();
                    }
                    elseif(count($arguments)==1)
                    {
                                return $this->getArrWithKey(implode(',' , $arguments));
                    }
            }

        }


}

/* Setting and getting values of array-> Arr[] */
$obj->setArr('name', 'Sau');
$obj->setArr('address', 'San Francisco');
$obj->setArr('phone', 7777777777);
echo $obj->getArr('name')."<br>";
print_r( $obj->getArr());
echo "<br>";

Upvotes: 0

Ian
Ian

Reputation: 900

I had the idea of something like:

function process( $param1 , $type='array' ) { switch($type) { case 'array': // do something with it break; case 'associative_array': // do something with it break; case 'int_array': // do something with it break; case 'string': // do something with it break; // etc etc... } }

Upvotes: 0

Jacob Christensen
Jacob Christensen

Reputation: 141

I know it's a bit old issue, but since php56 you can:

function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);

ref: http://php.net/manual/en/functions.arguments.php

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816462

If you are dealing with classes you can overload methods with __call() (see Overloading) e.g.:

class Foo {
    public function doSomethingWith2Parameters($a, $b) {

    }

    public function doSomethingWith3Parameters($a, $b, $c) {

    }

    public function __call($method, $arguments) {
      if($method == 'doSomething') {
          if(count($arguments) == 2) {
             return call_user_func_array(array($this,'doSomethingWith2Parameters'), $arguments);
          }
          else if(count($arguments) == 3) {
             return call_user_func_array(array($this,'doSomethingWith3Parameters'), $arguments);
          }
      }
   }    
}

Then you can do:

$foo = new Foo();
$foo->doSomething(1,2); // calls $foo->doSomethingWith2Parameters(1,2)
$foo->doSomething(1,2,3); // calls $foo->doSomethingWith3Parameters(1,2,3)

This might not be the best example but __call can be very handy sometimes. Basically you can use it to catch method calls on objects where this method does not exist.

But it is not the same or as easy as in Java.

Upvotes: 47

Thirler
Thirler

Reputation: 20760

No this isn't possible, because PHP cannot infer from the arguments which function you want (you don't specify which types you expect). You can, however, give default values to arguments in php.

That way the caller can give different amounts of arguments. This will call the same function though.

Example is:

function test($a = true)

This gives a default of true if 0 arguments are given, and takes the calling value if 1 argument is given.

Upvotes: 1

Xav
Xav

Reputation: 1

Overloading is not possible in PHP but you can get around it to some extend with default parameter values as explained in other responses.

The limit to this workaround is when one wants to overload a function/method according to the parameter types. This is not possible in PHP, one need to test the parameter types yourself, or write several functions. The functions min and max are a good example of this : if there is one parameter of array type it returns the min/max of the array, otherwise it returns the min/max of the parameters.

Upvotes: 0

broox
broox

Reputation: 3960

Like everyone else said, it's not supported by default. Felix's example using __call() is probably the best way.

Otherwise, if you are using classes that inherit from each other you can always overload the method names in your child classes. This also allows you to call the parent method.

Take these classes for example...

class Account {
  public function load($key,$type) {
    print("Loading $type Account: $key\n");
  }
}

class TwitterAccount extends Account {
  public $type = 'Twitter';

  public function load($key) {
    parent::load($key,$this->type);
  }
}

Then you can call them like so...

$account = new Account();
$account->load(123,'Facebook');

$twitterAccount = new TwitterAccount();
$twitterAccount->load(123);

And your result would be...

Loading Facebook Account: 123
Loading Twitter Account: 123

Upvotes: 2

Poindexter
Poindexter

Reputation: 2425

Everyone else has answers with good code explanations. Here is an explanation in more high level terms: Java supports Method overloading which is what you are referring to when you talk about function with the same name but different arguments. Since PHP is a dynamically typed language, this is not possible. Instead PHP supports Default arguments which you can use to get much the same effect.

Upvotes: 50

John Conde
John Conde

Reputation: 219824

Short answer: No. There can only be one function with a given name.

Longer answer: You can do this by creating a convoluted include system that includes the function with the right number of arguments. Or, better yet, you can take advantage of PHP allowing default values for parameters and also a variable amount of parameters.

To take advantage of default values just assign a value to a parameter when defining the function:

function do_something($param1, $param2, $param3 = 'defaultvaule') {}

It's common practice to put parameters with default values at the end of the function declaration since they may be omitted when the function is called and makes the syntax for using them clearer:

do_something('value1', 'value2'); // $param3 is 'defaultvaule' by default

You can also send a variable amount of parameters by using func_num_args() and func_get_arg() to get the arguments:

<?php
  function dynamic_args() {
      echo "Number of arguments: " . func_num_args() . "<br />";
      for($i = 0 ; $i < func_num_args(); $i++) {
          echo "Argument $i = " . func_get_arg($i) . "<br />";
      }
  }

  dynamic_args("a", "b", "c", "d", "e");
?>

Upvotes: 11

Related Questions