php 抽象类扩展另一个抽象类

php
2022-08-30 11:54:12

在 PHP 中,抽象类是否有可能从抽象类继承?

例如

abstract class Generic {
    abstract public function a();
    abstract public function b();
}

abstract class MoreConcrete extends Generic {
    public function a() { do_stuff(); }
    abstract public function b(); // I want this not to be implemented here...
}

class VeryConcrete extends MoreConcrete {
    public function b() { do_stuff(); }

}

( 抽象类在php中扩展抽象类?不给出答案)


答案 1

是的,这是可能的。

如果子类没有实现抽象超类的所有抽象方法,那么它也必须是抽象的。


答案 2

它会工作,即使你离开抽象函数b();在课堂上 更多混凝土.

但是在这个特定的例子中,我会将类“Generic”转换为一个接口,因为它除了方法定义之外没有更多的实现。

interface Generic {
    public function a(); 
    public function b();
}

abstract class MoreConcrete implements Generic {
    public function a() { do_stuff(); }
    // can be left out, as the class is defined abstract
    // abstract public function b();
}

class VeryConcrete extends MoreConcrete {
    // this class has to implement the method b() as it is not abstract.
    public function b() { do_stuff(); }
}

推荐