Create Abstract Class in PHP

Introduction

PHP 5 introduces "abstract" classes and methods. To declare a class as an abstract class, use the "abstract" keyword before the class name. When inheriting from an abstract class all methods marked abstract in the parent's class declaration must be defined by the sub class and in it any abstract methods defined as protected. The function implementaion must be defined as either protected or public but not private, furthermore the signatures of the methods must match.

When you declare a class as an "abstract" class , then this class may not be instantiated because it contains methods that are not implemented. In other words, when a class contains one or more abstract methods the class must be declared as abstract and this class is extended by its derived classes to implement its abstract methods. So an abstract class is a class with or without data members that provide some functionality and leave some functionality, which is implemented by its sub class.

To define a class as abstract the "Abstract" keyword is used. For example:

abstract class className {}

To define a method as abstract the "Abstract" keyword is also used but an abstract method can not be "private". For example:

abstract class className
{
abstract protected MethodName();
}

Example of an abstract class in PHP:

<?php

abstract
class AbstractClass
{

protected
$name;
abstract
protected function getName($name)  ; // declare a abstract method
public
function setName($name) // define a simple method
{
$
this->name=$name;
}
}

// concreteClass, extend the AbstractClass for Implementation
class
concreteClass extends AbstractClass
{

public
function getName($start)
{

return
$start .''. $this->name;
}

public
function date() // define a simple method, it returns today date
{
{

return
'<b>Today:</b> '. date('l, j-n-Y');
}
}
$obj=
new concreteClass();
$obj->setName(
"Ajeet");
echo $obj->getName(
"Hi !")."</br>";
echo $obj->date();

?>


Output

abstract-class-in-php.jpg


Similar Articles