Table of Contents



Introduction

OOP stands for Object-Oriented Programming.

Object-oriented programming can be defined as a programming model which is based upon the concept of objects. Objects contain data in the form of attributes and functions in the form of methods. In OOP, computer programs are designed using the concept of objects that interact with the real world. The most popular OOP languages are class-based, meaning that objects are instances of classes, which also determine their types.

For example, if we define a class of cars, its objects would be actual cars, which will have their own attributes (eg. company, model, type, power, etc.) and methods (eg. drive, park, get washed, etc.). The class provides a common set of methods and attributes for its objects to use. Each new object based on this class is called an instance (or occurrence) of the class.

Advantages of OOP

Object-oriented programming (OOP) has several advantages over traditional procedural programming:

  • OOP is faster and easier to execute.
  • OOP provides a clear structure for the programs.
  • OOP helps to keep the PHP code ‘clean’ by reducing the repetition of code. We extract the chunks of code that are oftenly used, place them in a single place and reuse them instead of repeating them. This makes the code easier to maintain, modify and debug.
  • OOP makes it possible to create fully reusable applications with less code and shorter development time.

Classes and Objects

A class is a template for objects, and an object is an instance of a class. When individual objects are created, they inherit all the properties and methods from the class, but each object will have different values for the properties.

Example

2 Classes, each with 4 instances.

Class Object Property
Fruit banana Calories = 25 cal/oz.
apple Calories = 15 cal/oz.
Lemon Calories = 8 cal/oz.
kiwi Calories = 17 cal/oz.
Car Toyota RAV4 Horsepower = 203 hp @ 6600 rpm
Honda CR-V Horsepower = 190 hp @ 5600 rpm
Toyota Highlander Horsepower = 295 hp @ 6600 rpm
Ford F-Series Horsepower = 290 hp @ 6500 rpm

In the above table, ‘Fruit’ is a class while

  • banana
  • apple
  • lemon
  • kiwi

are all objects (instances of the class). A property of the ‘Fruit’ class is ‘Calories’ and each object has a different value of this property (different calorie content).

Similarly, we define ‘Car’ as a class while

  • Toyota RAV4
  • Honda CR-V
  • Toyota Highlander
  • Ford F-Series

are all objects (instances of the class). A property of the ‘Car’ class is ‘Horsepower’ and each object has a different value of this property (different horsepower).