43

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)

6
  • 2
    Have you actually run the code before asking here? Commented Sep 1, 2011 at 11:32
  • @Jakub i think it is possible upto my knowledge Commented Sep 1, 2011 at 11:35
  • 1
    Yes. It did not work. Because... of abstract public function b(); in the second class. Without it it goes. Question answered Commented Sep 1, 2011 at 11:36
  • Why the hell would you not use interfaces and traits Commented Aug 18, 2016 at 15:29
  • 1
    @ied3vil Traits were not yet available in PHP when the question was posted. Commented Apr 12, 2019 at 16:36

3 Answers 3

45

Yes, this is possible.

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

Sign up to request clarification or add additional context in comments.

2 Comments

without abstract public function b(); in the second class it works... answered, thanks
Note that the order of the definitions matters. If you put the class VeryConcrete first, you will get 'Fatal error: Class 'MoreConcrete' not found' error. Be careful not to put the abstract cart before the horse.
6

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

Comments

5

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

Here is more detailed explanation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.