php 5 abstract class

In this blog i will cover introduction to PHP 5 abstract classes and method.

In this tutorial, I will explain about abstract class in PHP 5, how to declare and use of an abstract class.

php 5 Abstract Class:
Abstract class may contain one or more abstract methods. Abstract classes may not be instantiated. Child classes which inherits the property of abstract base class must define all the methods declared as abstract in class defination. Any class that contains at least one abstract method must be defined as abstract.
If the abstract method is defined as protected, the function implementation must be defined as either same visibility or lower e.g. If declared proteced in parent then child class must declare it either protected or public, not a private.

Furthermore the signatures of the abstract methods must match, i.e. the type hints and the number of required arguments must be the same with parent class. i.e. If the child class defines an optional argument, where the abstract method’s signature does not, there is no conflict in the signature. This also applies to constructors as of PHP 5.4. Before 5.4 constructor signatures could differ.

abstract class DemoAbstractClass
{
    // 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 FirstChild extends DemoAbstractClass
{
    protected function getValue() {
        return "ConcreteClass1";
    }
    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass1";
    }
}
class SecandChild extends DemoAbstractClass
{
    public function getValue() {
        return "ConcreteClass2";
    }
    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass2";
    }
}
$class1 = new FirstChild;
$class1->printOut();
echo $class1->prefixValue('prefix1_') ."\n";
$class2 = new SecandChild;
$class2->printOut();
echo $class2->prefixValue('prefix2_') ."\n";
Share this nice post: