dongtanhe4607 2017-10-04 15:21
浏览 29
已采纳

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

}
  • 写回答

1条回答 默认 最新

  • dqu92800 2017-10-04 15:29
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么