PHP中的方法重载是不好的做法?

问题描述:

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

}

尝试实现方法重载(不要与来自 PHP手册),不容易有明显的权衡,因为PHP的本质你必须有一个方法和 if code>或 switch code> 语句里面提供重载,它创建了很难在长方法中读取的过程代码。 p>

在PHP中有方法重载是否有任何优势,是否可以通过其他任何方式实现? p>

 类MyClass {
 
公共函数doMany($ input){
 
 if if(is_array($ input)){
 ... 
} 否则if(is_float($ input)){
 ... 
} 
 
} 
 
}} 
  code>  pre> 
 
 

与传统方法相比 p>

 类MyClass {
 
公共函数doArr  ay(数组$输入){
 ... 
} 
 
公共函数doFloat(float $ input){
 ... 
} 
 
} 
  code>  pre  > 
  div>

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.