dpxw7293 2010-08-25 20:55
浏览 40
已采纳

继承的工厂方法应该返回自己的类的实例而不是继承的类

I have a class that has a complex static factory method, lets call it ClassA. I have extended ClassA into ClassB and I want ClassB's factory method to do everything that ClassA's factory method does, except return a ClassB.

class ClassA{
   static public function Factory($construct_args, $contents){
      $new = new ClassA($construct_args);
      //Does lots of stuff with $contents
   }
}

class ClassB extends ClassA{
   //specialty methods and properties
}

echo get_class(ClassB::Factory($construct_args, $contents);

This should echo ClassB

Is there a way I can use ClassA's Factory Method without copy-pasting it to ClassB? I am using PHP5, but not 5.3.0.

  • 写回答

3条回答 默认 最新

  • doubeng3412 2010-08-25 21:09
    关注

    To do exactly what you want you need Late Static Binding, so you need PHP 5.3. It can not be done as you want in PHP 5.2. People have tried.

    The workarounds I've seen/used for 5.2 are

    1. As you mentioned (and don't want to do) copy your factory method into each class

    2. Require end-users of the factory to supply the name of the class they're instantiating as an argument

    3. Require your factories to implement an interface or have them inherit from an abstract class (or just know the convention) that requires the definition of a static "getClassName" method, which will be used in the factory. This is similar to number one, but some people prefer it as it allows their factory method to remain in the "bottom" class.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口