Tuesday 28 May 2013

Difference between Abstract class and Interface in PHP

Difference between Abstract class and Interface in PHP

S.No
Abstract Class
Interface
1
For abstract class, a method must be declared as abstract. In class, at-least one method must be declared as abstract.


Variable can not be declared
For Interface, class must be declared as Interface.

In interface, all methods by default all are abstract methods.


Variable can not be declared
2
The Abstract methods can declare with Access modifiers like public, private, protected.

When implementing in subclass these methods must be defined with the same visibility (Like public, protected).
All methods are public in interface.
3
Abstract class can contain variables, concrete methods and constants.Interfaces cannot contain variables and concrete methods except constants.
4
A class can Inherit only one Abstract class
and
Multiple inheritance is not possible for Abstract class.
A class can implement many interfaces
and
Multiple interface inheritance is possible.


   



Similarity between abstract and interface classes

1) We can not create object of abstract and interfaces.

2) Abstract method must be there in abstract and interface

3) We have to defined all the methods which are abstract in base class.



Example of Interface
//Interface
interface car {

    public function audio();

    public function video();
}

//how to implements interface
class mycar implements car {

    public $owner = 'Arun';

    public function audio(){
        return 'Audio functionality.';
    }

    public function video(){
        return 'Video functionality.';
    }

    public function owner() {
        return $this->owner;
    }

}

$mycarObj = new mycar();
echo $mycarObj->audio(); //Audio functionality
echo $mycarObj->video(); //video functionality
echo $mycarObj->owner(); //Arun



Example of Abstract
//Abstract class
abstract class car {
    //Abstract method
    abstract public function audio();

    public function video() {
        return 'video functionality.';
    }

}

class mycar extends car {
    public $owner='Arun';
    public function audio() {
        return 'Audio functionality.';
    }
    public function owner() {
        return $this->owner;
    }    

}

$mycarObj = new mycar();
echo $mycarObj->audio(); //Audio functionality
echo $mycarObj->video(); //video functionality
echo $mycarObj->owner(); //Arun