PHP Object Oriented Programming (OOPs) concept Tutorial with Example

Let’s talk about PHP OOPs.

Mosharrf Hossain
Mh Mohon
3 min readFeb 12, 2019

--

What is OOPs?

Oobject Oriented is an approach to software development that models application around real world objects such as employees, cars, bank accounts, etc. A class defines the properties and methods of a real world object. An object is an occurrence of a class.

The three basic components of object orientation are;

  • Object oriented analysis — functionality of the system
  • Object oriented designing — architecture of the system
  • Object oriented programming — implementation of the application

Object Oriented Programming Principles

The three major principles of OOP are;

Encapsulation — this is concerned with hiding the implementation details and only exposing the methods also can be called wrapping obj/data. The main purpose of encapsulation is to:

  • Reduce software development complexity — by hiding the implementation details and only exposing the operations, using a class becomes easy.
  • Protect the internal state of an object — access to the class variables is via methods such as get and set, this makes the class flexible and easy to maintain.
  • The internal implementation of the class can be changed without worrying about breaking the code that uses the class.

— Increase Security

— Using “get” and “set” methods etc.

Inheritance — this is concerned with the relationship between classes. The relationship takes the form of a parent and child. The child uses the methods defined in the parent class. The main purpose of inheritance is;

  • Re-usability– a number of children, can inherit from the same parent. This is very useful when we have to provide common functionality such as adding, updating and deleting data from the database.

— Using extends keyword

Polymorphism — this is concerned with having a single form but many different implementation ways. The main purpose of polymorphism is:

  • Simplify maintaining applications and making them more extendable.
  • Same function can be used for different purposes
  • function name will remain same but it take different number of arguments and can do different task.
  • Method Overriding.

— Using implements keyword

Example:

There are another two principles are.

  • Interface — It is similar to a class. It only defines the methods and parameters only nothing else.
  • Abstract class — it is a class that cannot be used to create an object directly. Its purpose is to provide partial or whole implementations of common methods.

Create Abstract class

“abstract class” means the class cannot be used directly to php create object.

create the interface

“interface” is the keyword for creating interfaces.

Let’s now create the concrete classes that will extend the DBCommonMethods class and extend the DBInterface interface with full code:

Reference from Guru.

--

--