简体   繁体   中英

php abstract class extending another abstract class

Is it possible in PHP, that an abstract class inherits from an abstract class?

For example,

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(); }

}

( abstract class extends abstract class in php? does not give an answer)

Yes, this is possible.

If a subclass does not implements all abstract methods of the abstract superclass, it must be abstract too.

Yes it is possible however your code would not work if you called $VeryConcreteObject->b()

Here is more detailed explanation.

It will work, even if you leave the abstract function b(); in class MoreConcrete.

But in this specific example I would transform class "Generic" into an Interface, as it has no more implementation beside the method definitions.

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(); }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM