PHP5 Abstracts

Abstract classes and methods are introduced in PHP 5. The concept behind the abstract class is that we need to extend this class by its descendant class(es). If a class contains abstract method then the class must be declared as abstract. Any method which is declared as abstract must not have the implementation part but the declaration part only.

It is a way to share information across classes without actually creating a class. If you will never have a need for a particular class to be instantiated, yet want to provide members and methods that can be used by all children, use an abstract. In PHP we have only single inheritance, so your (child) class would just inherit (extend) from the abstract class.

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

To define a class as Abstract, the keyword abstract is to be used e.g. abstract class ClassName { }

Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method’s signature – they cannot define the implementation.

Example Given Blow:

abstract class AbstractClass
// Force Extending class to define this method
abstract protected function getValue();
abstract protected function prefixValue($prefix);
// Common method
public function printOut() {
print $this->getValue() . “\n”;
}class ConcreteClass1 extends AbstractClass
protected function getValue() {
return “ConcreteClass1”;

public function prefixValue($prefix) {
return “{$prefix}ConcreteClass1”;

class ConcreteClass2 extends AbstractClass
public function getValue() {
return “ConcreteClass2”;

public function prefixValue($prefix) {
return “{$prefix}ConcreteClass2″;

$class1 = new ConcreteClass1;
echo $class1->prefixValue(‘FOO_’) .”\n”;

$class2 = new ConcreteClass2;
echo $class2->prefixValue(‘FOO_’) .”\n”;






Bansal Sumit

To seek challenging roles and to achieve excellence in the field of Open Source Web Technology with a profound spirit of commitment and dedication.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *