PHP Abstract Class


 

PHP Abstract Class

In this tutorial we will study about abstract class in PHP, how to declare, use an abstract class etc. Examples will help you to understand the concepts of abstract class more precisely.

In this tutorial we will study about abstract class in PHP, how to declare, use an abstract class etc. Examples will help you to understand the concepts of abstract class more precisely.

PHP Abstract Class:

Abstract classes and methods are introduced in PHP 5. The concept behind the abstract class is that we need to extend this class by its descendant class(es). If a class contains abstract method then the class must be declared as abstract. Any method which is declared as abstract must not have the implementation part but the declaration part only.

The child classes which inherits the property of abstract base class, must define all the methods declared as abstract.

PHP Abstract Class Example:

<?php

abstract class One{

public function disp(){

echo "Inside the parent class<br/>";

}

}

class Two extends One{

public function disp(){

echo "Inside the child class<br/>";

}

}

class Three extends One{

//no method is declared

}

$two=new Two();

echo "<b>Calling from the child class Two:</b><br/>";

$two->disp();

echo "<b>Calling from the child class Three:</b><br/>";

$three=new Three();

$three->disp(); 

?>

Output:

Calling from the child class Two:
Inside the child class
Calling from the child class Three:
Inside the parent class

 

Example:

<?php

0

abstract class One{

abstract function disp();

}

1

class Two extends One{

public function disp(){

echo "Inside the child class<br/>";

2

}

}

class Three extends One{

3

public function disp(){

echo "Inside the child class 2<br/>";}

}

4

$two=new Two();

echo "<b>Calling from the child class Two:</b><br/>";

$two->disp();

5

echo "<b>Calling from the child class Three:</b><br/>";

$three=new Three();

$three->disp();

6

?>

Output:

Calling from the child class Two:
Inside the child class
Calling from the child class Three:
Inside the child class 2

 

7

 

 

Ads