2

I am studying the differences between Abstract and Interface and I read some sentence saying

A child class can only extend a single abstract (or any other) class, whereas an interface can extend or a class can implement multiple other interfaces.

I understand when he says, “A child class can only extend a single abstract (or any other) class,” he means:

class first
{
    public function Search()
    {
        return 'Hellow';
    }
}

abstract class first2 extends first
{

}

class second extends first2
{   

}

$ob = new second();
echo $ob->Search();

However, I didn’t understand the rest of his sentence, where he says, “whereas an interface can extend or a class can implement multiple other interfaces.”

Could someone please explain his last sentence and add a code example? Thank you all and have a nice day.

2

1 Answer 1

4

You can implement more than one interface

interface C {
  public function method1();
}

interface D {
  public function method2();
}

class A implements C,D {

   //implement from interface C
   public function method1() {

   }
   //implement from interface D
   public function method2() {

   }
}

Here you will need implement methods from interface C and D. You can also extend interfaces within interfaces, like normal classes.

interface D extends C{}

It's useful when well you need some common methods. so you write "schema" into interface what methods you are expecting from base class to be implemented.

While abstract is single extended class, you canot create instance for it, only extend. It's useful when you want have some base class with common functionality or abstract methods what should be implemented later.

More you can always read at php.net - interfaces

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

3 Comments

Base classes are almost always bad design. The idea of inheritance is not to collect commonly used functionality in some sort of Blob/God class. The idea of inheritance is to have some well defined Superclass and then have special cases / variations of that in the subclasses.
Yes Blob classes is evil i am not speaking about it, there is sometimes when you need common functionality, take for ex. MVC abstract Model, Controller classes there will be methods who is shared and have common functionality. Idea of inheritance is also avoid code repeating-dublicates. Not mentioning extending your code.
In general, it is better to favor composition over inheritance

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.