i

PHP Tutorial

PHP-Abstract Classes

Abstract classes in PHP is a class that cannot be instantiated i.e. you cannot create an object for the abstract class. Abstract class can have both abstract methods and non- abstract methods but at least one method should be abstract in an abstract class. You can declare abstract classes and methods using abstract keyword. Abstract methods are not implemented in the base class and are just declared. The implementation is done in the child class of this abstract base class.

Syntax:

abstract class class_name

{

abstract public function function1();

public function function2();

}

For example:

abstract class Fruit{

abstract function message();

}

class Apple extends Fruit {

function message() {

echo “ An apple a day keeps a doctor away”;

}

}

$Apple = new Fruit(); // It will give error because Fruit is abstract class

$Apple = new Apple();

$Apple -> message();

?>

You can also create a constructor for the abstract class like other programming languages. When a child class is inherited using abstract class the name of the abstract method should be same in the derived class. The number of parameters should also be same as in the abstract method and additional parameters can also be added in the derived class methods.

If you try to implement the abstract method in the abstract class it will display and error message at runtime. So, you need a child class to implement the methods of an abstract class.