Can we have two functions with the same name in php why or why not?

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?

Nội dung chính

  • Can you have two functions with the same name in a PHP class?
  • Can 2 functions have the same name?
  • Can we declare two functions with the same name in PHP Why or why not?
  • Is the process of using the same name for two or more functions?
  • Can you have two functions with the same name in C?
  • Is overloading possible in PHP?

Luís Cruz

14.4k16 gold badges69 silver badges98 bronze badges

asked Jan 27, 2010 at 14:33

2

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.

answered Jan 27, 2010 at 14:48

PoindexterPoindexter

2,37616 silver badges19 bronze badges

1

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.

answered Jan 27, 2010 at 14:54

Felix KlingFelix Kling

768k171 gold badges1068 silver badges1114 bronze badges

6

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:


answered Jan 27, 2010 at 14:40

John CondeJohn Conde

214k98 gold badges447 silver badges489 bronze badges

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

Kukeltje

12.1k4 gold badges21 silver badges46 bronze badges

answered Jan 27, 2010 at 14:40

YOUYOU

116k32 gold badges184 silver badges216 bronze badges

1

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

answered Feb 13, 2011 at 22:44

brooxbroox

2,90030 silver badges24 bronze badges

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.

Peter Gluck

8,1001 gold badge37 silver badges35 bronze badges

answered Jan 27, 2010 at 14:37

ThirlerThirler

19.7k13 gold badges64 silver badges89 bronze badges

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: //php.net/manual/en/functions.arguments.php

answered Apr 12, 2017 at 7:40

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.

answered Jun 16, 2011 at 9:35

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

answered May 30, 2017 at 12:25

IanIan

9002 gold badges8 silver badges19 bronze badges

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']."
"; print_r[ $obj->getArr[]]; echo "
";

answered Aug 24, 2018 at 0:21

Can you have two functions with the same name in a PHP class?

No. PHP does not support classic overloading. [It does implement something else that is called overloading.]

Can 2 functions have the same name?

Yes, it's called function overloading. Multiple functions are able to have the same name if you like, however MUST have different parameters.

Can we declare two functions with the same name in PHP Why or why not?

NOT provides the ability to declare multiple methods with the same name but different types. This is because PHP compiler must interpret f[$integer,$string] as the same function that f[$string,$integer] .

Is the process of using the same name for two or more functions?

The process of having two or more functions with the same name, but different parameters, is known as function overloading. The function is redefined by either using different types of arguments or a different number of arguments.

Can you have two functions with the same name in C?

Function overloading is a feature of a programming language that allows one to have many functions with same name but with different signatures.

Is overloading possible in PHP?

PHP does not support method overloading. In case you've never heard of method overloading, it means that the language can pick a method based on which parameters you're using to call it. This is possible in many other programming languages like Java, C++.

Can you have two functions with the same name in a PHP class?

No. PHP does not support classic overloading. [It does implement something else that is called overloading.]

Can we declare two functions with the same name in PHP Why or why not?

NOT provides the ability to declare multiple methods with the same name but different types. This is because PHP compiler must interpret f[$integer,$string] as the same function that f[$string,$integer] .

Can two functions have the same name?

Yes, it's called function overloading. Multiple functions are able to have the same name if you like, however MUST have different parameters.

Can we use same named functions in more than one classes defined in a program?

Yes, we can define multiple methods in a class with the same name but with different types of parameters.

Chủ Đề