Abstraction in php

Abstract Classes in PHP

Abstract classes must have at least one abstract method. In php we can make class abstract using abstract keyword.
All Child classes implementing abstract class should give implementation of abstract methods which are in parent class. Abstract class can have abstract as well as non abstract methods

abstract class AbstractMainClass
{
    abstract protected function fun1();
    abstract protected function prefixValueFun($prefix);

    // Common method
    public function outPut() {
        print $this->fun1() . "\n";
    }
}

class NormalClass1 extends AbstractMainClass
{
    protected function fun1() {
        return "NormalClass1";
    }

    public function prefixValueFun($prefix) {
        return "{$prefix}NormalClass1";
    }
}

class NormalClass2 extends AbstractMainClass
{
    public function fun1() {
        return "NormalClass2";
    }

    public function prefixValueFun($prefix) {
        return "{$prefix}NormalClass2";
    }
}

$class1 = new NormalClass1;
$class1->outPut();
echo $class1->prefixValueFun('FOO_') ."\n";

$class2 = new NormalClass2;
$class2->outPut();
echo $class2->prefixValueFun('FOO_') ."\n";

Output

NormalClass1
FOO_NormalClass1
NormalClass2
FOO_NormalClass2

Leave a Reply

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