doushi2902 2017-06-16 16:03
浏览 34
已采纳

PHP OOP继承问题

I have an inheritance issue. Consider I have a parent class A and a derived class B from A and a derived Class C from A again.

Let's say, class B & C both override method seed() from class A. Also clases A & B & C all implement a static function seedAll().

My question is: How do I call seedAll for B & C from the seedAll function of A without explicitly specifying the class B & C, so that in the future, should I have a class D similar to class B & C, I need not modify the seedAll function of class A to call the seedAll functions of classes B, C & D.

abstract class A
{
    public static function seedAll() {
        //How do I call seedAll of all the derived classes of Seeder?
    }

    abstract protected function seed();
    // // Common method
    // public function printOut() {
    //     print $this->getValue() . "
";
    // }
}

class B extends A
{
    private $name;

    function __construct($name) {
        $this->name = $name;
    }

    public static function seedAll() {
        $seeder1 = new B("name1");
        $seeder1 = new B("name2");
    }

    function seed() {
        echo $this->name;
    }
}


  class C extends A
    {
        private $name;

        function __construct($name) {
            $this->name = $name;
        }

        public static function seedAll() {
            $seeder1 = new C("name1");
            $seeder1 = new C("name2");
        }

        function seed() {
            echo $this->name;
        }
    }
  • 写回答

1条回答 默认 最新

  • drzip28288 2017-06-16 16:21
    关注

    See how to obtain all subclasses of a class in php for how to get all the subclasses. You can then loop over them and call their seedAll() methods.

    abstract class A
    {
        public static function seedAll() {
            $subclasses = getSubclassesOf("A");
            foreach ($subclasses as $class) {
                $class::seedAll();
            }
        }
    
        abstract protected function seed();
        // // Common method
        // public function printOut() {
        //     print $this->getValue() . "
    ";
        // }
    }
    

    getSubclassesOf function:

    function getSubclassesOf($parent) {
        $result = array();
        foreach (get_declared_classes() as $class) {
            if (is_subclass_of($class, $parent))
                $result[] = $class;
        }
        return $result;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题