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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置