Roman Toasov
Roman Toasov

Reputation: 821

Method overloading in PHP is bad practice?

Trying to achieve method overloading using PHP (don't confuse with overloading definition from PHP manual), is not easy there is clear trade off, because of nature of PHP you have to have one method and if or switch statement inside to provide overloading, it creates procedural code that is difficult to read in long methods.

Is there any advantage of having method overloading in PHP, can it be achieved in any other way?

class MyClass {

   public function doMany($input) {

      if (is_array($input)) {
         ...
      } else if (is_float($input)) {
         ...
      }

   }

}

versus traditional approach

class MyClass {

   public function doArray(array $input) {
      ...
   }

   public function doFloat(float $input) {
      ...
   }

}

Upvotes: 1

Views: 4183

Answers (1)

Andrei
Andrei

Reputation: 3588

The traditional approach would be:

class Aclass {
  public function doStuff(int $a) {
    // return other stuff
  }

  public function doStuff(float $a) {
    // return other stuff
  }
}

Notice the same function name just different type for the paramaters.

Your first approach is usually the way to go if you want to simulate overloading in php. Generally speaking you don't really need overloading in PHP since it's loosely type and by definition you can't really have overloading.


To answer your question. If you really need to have overloading, then your first approach seems appropriate. Use a switch to make it more readable.

Disclaimer: While you can do that, I don't recommend it. Heck, you can do just about anything if you want to. It doesn't mean you should.

Upvotes: 4

Related Questions