Abstract Class in PHP

In this article I explain how to create an abstract class and methods in PHP
  • 2097

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 implementation 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.

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-in-php.jpg

© 2019 DotNetHeaven. All rights reserved.