EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Abstract Class in PHP

Home » Software Development » Software Development Tutorials » PHP Tutorial » Abstract Class in PHP

Abstract class in PHP

What is an Abstract Class?

Like abstract class, there are abstract methods as well. We declare both the abstract method and the abstract class with the abstract keyword. In this topic, we are going to learn about Abstract class in PHP.

As per the concept of inheritance, the parent class is extended by the derived class.  The methods in the parent class are implemented or defined by the derived classes. PHP makes a way for the parent class to be more specific, by making the use of abstract class and abstract methods.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

The abstract class compulsorily contains one method as abstract. Also, this abstract class can have other non-abstract methods as well.

Syntax

Syntax of Abstract Class with one method as abstract.

abstract class DemoAbstractClass() {
abstract public function DemoAbstractMethod();
}

Abstract Method

abstract public function DemoAbstractMethod();

How does Abstract Class work in PHP?

In this article, we will learn the working of the abstract class and it goes like this.

Now as we know that an abstract class compulsorily has one method as abstract.

There can be non-abstract methods also. The abstract method has only the declaration in the base class. Meaning that it has only names and parameters with no other code.

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,694 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

To define the method further, and to work with the method, this method needs to be implemented in the derived class which extends the base class. Also, remember that this abstract class cannot be instantiated to create objects, but the class derived from the base class can be instantiated to create objects.

Examples of Abstract Class in PHP

Here are some examples of Abstract class in PHP given below

Example #1

In the below program we learn what happens when an object of abstract class is created.

Abstract class Student is created containing one abstract method favouriteSubject() method of the Student Class and two other not abstract methods like setRollNo() and getRollNO() which sets and gets the student’s role, which is done by creating the object of the derived class (extending the base class).

<?php
abstract class Student {
protected $m;
public function setRollNo($rollno) {
return $this->m = $rollno;
}
public function getRollNo() {
return $this->m;
}
abstract public function favouriteSubject()
}
class Radha extends Student {
public function favouriteSubject() {
return "English";
}
}
$obj = new Student;    //this statement throws error as we cannot create object of class Student as it is defined as abstract
$obj = new Radha;  //this statement does not throws error and executes correctly
$obj->favouriteSubject();
?>

Output :

abstract class in php output 1

Example #2

This example is explained step by step below,  after the program output along with the code from this example.

Code 

abstract class Student{
protected $m;
abstract public function calulatePercentage();
public function setMarks($marks) {
return $this->m = $marks;
}
public function favoriteSubject() {
return 'Favorite subject is English';
}
}
class Ram extends Student{
public function calulatePercentage(){
$percentage = ($this->m /100 ) * 100;
return 'The percentage of Ram is '.$percentage. '%' .'<br>';
}
}
class Sherry extends Student{
public function calulatePercentage(){
$percentage = ($this->m /100 ) * 100;
return 'The percentage of Sherry is '.$percentage. '%' .'<br>';
}
public function favoriteSubject() {
return 'Favorite subject is Maths';
}
}
$ram = new Ram();
$ram->setMarks(92);
echo $ram->calulatePercentage();
echo $ram->favoriteSubject();
echo '<hr>';
$sherry = new Sherry();
$sherry->setMarks(97);
echo $sherry->calulatePercentage();
echo $sherry->favoriteSubject();

Output :

abstract class in php output 2

An abstract class can be termed as a skeleton for derived classes. In this above example, we declare the abstract class Student and a property called $m for marks of the student.

Explanation of Example #2

abstract class Student {
abstract public function calulatePercentage();
}

An abstract class can be termed as a skeleton for derived classes. In this example, we declare the abstract class and methods along with other methods.

In the above example, we have declared abstract class Students with abstract methods to calculate the percentage of the student, along with marks given.

Also, we have created methods (which are not abstract) to set the Marks of the student and to get the favorite subject of the student.

abstract class Student{
abstract public function calulatePercentage();
public function setMarks($marks) {
return $this->m = $marks;
}
public function favoriteSubject() {
return 'Favorite subject is English';
}
}

To create objects of abstract class Student we have to extend the class Student and create derived classes out of it. The base class uses extends keyword to allow the base class to extend. Once the class is extended, we can now use the base class methods.

In the above example, Ram is the derived class that extends the base class Student. It uses the extends keyword. Now we have calculated percentage() method to calculate the percentage of the marks obtained by Ram.

class Ram extends Student{
public function calulatePercentage(){
$percentage = ($this->m /100 ) * 100;
return 'The percentage of Ram is '.$percentage. '%' .'<br>';
}
}

Declaring one more class which extends the base class Student for us to learn more.

In the above example, we have created Sherry as the derived class created from the base class Student. This uses the extends keyword. It has two functions one which was declared as abstract, the calulatePercentage() method in the base class the other is the favoriteSubject() method which is not abstract.

class Sherry extends Student{
public function calulatePercentage(){
$percentage = ($this->m /100 ) * 100;
return 'The percentage of Sherry is '.$percentage. '%' .'<br>';
}
public function favoriteSubject() {
return 'Favorite subject is Maths';
}
}

Now we create the object of the base class and the object of the derived class, which throws an error. Because we cannot instantiate the class declared as abstract.

Thus only the object of the derived class can be created. Once this is done, using this object we will call the abstract method and not abstract method both as seen below.

$ram = new Ram();
$ram->setMarks(92);
echo $ram->calculatePercentage();
echo $ram->favoriteSubject();
echo '<hr>';
$sherry = new Sherry();
$sherry->setMarks(97);
echo $sherry->calculatePercentage();
echo $sherry->favoriteSubject();

Conclusion

In this article, I hope you learned about how the abstract class is declared, how it works, how it is extended using extends keyword, how the abstract method is declared in the base class and how it is implemented in the derived class. The examples explained will help you learn the concept at ease. Hope it was prepared to be useful enough to grasp and practice more.

Recommended Articles

This is a guide to the Abstract class in PHP. Here we discuss How does Abstract Class work in PHP with the sample code, and appropriate outputs. You may also have a look at the following articles to learn more –

  1. Object in PHP
  2. PHP Constants
  3. Cookie in PHP
  4. Patterns in PHP

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

2 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More