Вы находитесь на странице: 1из 8

Difference between Abstract class and Interface in PHP

S.No 1 Abstract Class For abstract class a method must be declared as abstract. Abstract methods doesnt have any implementation. The Abstract methods can declare with Access modifiers like public, internal, protected. When implementing in subclass these methods must be defined with the same (or a less restricted) visibility. Abstract class can contain variables and concrete methods. A class can Inherit only one Abstract class and Multiple inheritance is not possible for Abstract class. Interface For interface all the methods by default are abstract methods only. So one cannot declare variables or concrete methods in interfaces. All methods declared in an interface must be public.

3 4

Interfaces cannot contain variables and concrete methods except constants. A class can implement many interfaces and Multiple interface inheritance is possible.

The above differentiation suggests when to use an abstract class and when to use an interface: If you want to provide common implementation to subclasses then an abstract class is used, If you want to declare non-public members, the use abstract method In case of abstract class, you are free to add new public methods in the future, If you're confirm regarding the stablity of the API for the long run then use an interface If you want to provide the implementing classes the opportunity to inherit from other sources at the same time then use an interface.

In general, prefer interfaces if you don't need to use an abstract class, because they provide more design flexibility. Abstract Class Example An abstract class is a class with or without data members that provides some functionality and leaves the remaining functionality for its child class to implement. The child class must provide the functionality not provided by the abstract class or else the child class also becomes abstract. Objects of an abstract and interface class cannot be created i.e. only objects of concrete class can be created. abstract class Furniture { private $height, $width, $length; public function setData($h, $w, $l) { $this->height = $h; $this->width = $w; $this->length = $l; }

//this function is declared as abstract and hence the function //body will have to be provided in the child class public abstract function getPrice(); } class BookShelf extends Furniture { private $price; public function setData($h, $w, $l, $p) { parent::setData($h, $w, $l); $this->price = $p; } //this is the function body of the parent abstract method public function getPrice() { return $this->price; } } $bookShelf = new BookShelf(); $bookShelf->setData(10,20,10,30); echo $bookShelf->getPrice(); Output : 30 In the above example, the method getPrice() in class Furniture has been declared as Abstract. This means that its the responsibility of the child class to provide the functionality of getPrice(). The BookShelf class is a child of the Furniture class and hence provides the function body for getPrice(). Private methods cannot be abstract : If a method is defined as abstract then it cannot be declared as private (it can only be public or protected). This is because a private method cannot be inherited. Interface Example An interface is a contract between unrelated objects to perform a common function. An interface enables you to specify that an object is capable of performing a certain function, but it does not necessarily tell you how the object does so, this means that it leaves for classes implementing an interface to define its behaviour. To extend from an Interface, keyword implements is used. We can have a class extend from more than one Interface. interface Storable {

function getContentsAsText(); } class Document implements Storable { public function getContentsAsText() { return "This is Text of the Document\n"; } } class Indexer { public function readAndIndex(Storable $s) { $textData = $s->getContentsAsText(); //do necessary logic to index echo $textData; } } $p = new Document(); $i = new Indexer(); $i->readAndIndex($p); output : This is Text of the Document In the above example, Document and the Indexer class are two independant classes. The Indexer class is designed to index the contents of any text. Using the Storable interface above, we declare a method getContentsAsText() in the Document class. Because the Indexer class is only concerned with the TEXT, hence we can call getContentsAsText() method on the object of Document. This way any class if it implements the method getContentsAsText() can get indexed.

Difference between Abstract Class and Interface


Abstract Classes 1. An abstract class can provide some functionality and leave the rest for derived class. 2. The derived class may or may not override the concrete functions defined in base class. 3. The child class extended from an abstract class should logically be related. Interface

1. An interface cannot contain any functionality. It only contains definitions of the methods. 2. The derived class must provide code for all the methods defined in the interface. 3. Completely different and non-related classes can be logically be grouped together using an interface. Combined Example Of Abstract Class And Interface : abstract class animal { abstract function getowned(); private $age; protected function __construct($age) { $this->age = $age; } public function getage() { return $this->age; } } interface insurable { public function getvalue(); } class pet extends animal implements insurable { private $name; public function __construct($name,$age) { parent::__construct($age); $this->name = $name; } public function getname() { return $this->name; } public function getowned() { return ("Owner String"); } public function getvalue() { return ("Priceless"); } } class house implements insurable { public function getvalue() { return ("Rising fast"); } }

$charlie = new pet("Charlie",6); $catage = $charlie -> getage(); $catname = $charlie -> getname(); print "$catname is $catage years old!<br><br>"; if ($charlie instanceof pet) print ("charlie is a pet<br>"); if ($charlie instanceof animal) print ("charlie is an animal<br>"); if ($charlie instanceof house) print ("charlie is a house<br>"); if ($charlie instanceof insurable) print ("charlie is insurable<br>"); output : Charlie is 6 years old! charlie is a pet charlie is an animal charlie is insurable Final Example : // No company just has "employees", all employees have a particular function or belong to a group. // So, we don't want employee to be a concrete (one that can be instantiated) class. Lets create an abstract. abstract class Employee { protected $employeeID=''; protected $annualSalary=NULL; abstract protected function setEmployeeID(); abstract protected function setAnnualSalary(); public function getEmployeeID() { return $this->employeeID; } public function getAnnualSalary() { return $this->annualSalaryID; } } //Now lets define some interfaces based on the description above //canHackTheSystem and canTakeLongVacations are the adjectives //they can be used to group employees in a manner that is different then just their job interface canHackTheSystem {

public function getSecurityClearance(); } interface canTakeLongVacations { public function getHRApproval(); } // and now, finally our classes. Notice the implements keyword to use interfaces class Engineer extends Employee implements canHackTheSystem { protected function setEmployeeID() { //read from db, etc. } protected function setAnnualSalary() { //beg HR for a raise } //required by the interface 'canHackTheSystem' public function getSecurityClearance() { //of course, they have all access } } class Executive extends Employee implements canTakeLongVacations { protected function setEmployeeID() { //read from super-special db, etc. } protected function setAnnualSalary() { //definitely a large number } //required by the interface 'canTakeLongVacations' public function getHRApproval() { //all those bribes and gifts paid off } } //instantiate $engineer = new Engineer; $executive = new Executive;

//ok, with these defined and instantiated, we can do cool stuff like this //a more applicable example might be if the object was instantiated via a Factory //but hopefully you get the idea. if ($executive instanceof canTakeLongVacations) { // schedule meetings during the winter months echo "schedule meetings during the winter months"; } if ($engineer instanceof canHackTheSystem) { // don't fire this person, they hold the keys to the kingdom echo "<br>don't fire this person, they hold the keys to the kingdom"; } class SeniorEngineer extends Engineer implements canHackTheSystem, canTakeLongVacations { //she can do it all public function getHRApproval() { } } Output : schedule meetings during the winter months don't fire this person, they hold the keys to the kingdom Static in PHP Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can). Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static. Static properties cannot be accessed through the object using the arrow operator ->. Calling non-static methods statically generates an E_STRICT level warning. Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object. Example 1 : class Foo { public static $my_static = 'foo';

public function staticValue() { return self::$my_static; } } class Bar extends Foo { public function fooStatic() { return parent::$my_static; } } print Foo::$my_static . "\n"; $foo = new Foo(); print $foo->staticValue() . "\n"; print $foo->my_static . "\n"; // Undefined "Property" my_static since static variable can not call with "->". print $foo::$my_static . "\n"; $classname = 'Foo'; print $classname::$my_static . "\n"; // As of PHP 5.3.0 print Bar::$my_static . "\n"; $bar = new Bar(); print $bar->fooStatic() . "\n"; Output : foo foo foo foo foo foo Example 2 : class Foo { public static function aStaticMethod() { echo "here<br>"; } } Foo::aStaticMethod(); $classname = 'Foo'; $classname::aStaticMethod(); // As of PHP 5.3.0 Output : here here

//Will not print anything ,