Object Oriented Programming (OOPs) Concept in Php

Sagardhiman
5 min readDec 11, 2023
Object Oriented Programming (OOPs) Concept in Php
Object Oriented Programming (OOPs) Concept in Php

In object-oriented programming (OOP), classes and objects are fundamental concepts that allow you to model and organize your code in a more modular and reusable way. Let’s break down these concepts in the context of PHP, using simple language and a real-time example.

Class:

A class is like a blueprint or a template that defines a type of object. It encapsulates the properties (attributes) and behaviors (methods) that objects of that type will have. In PHP, you define a class using the class keyword.

<?php
class Dog {

public $name;
public $breed;

public function bark() {
echo "Woof! Woof!";
}

public function fetch() {
echo "{$this->name} is fetching.";
}
}
?>

In this example, we’ve created a Dog class with properties ($name and $breed) and methods (bark and fetch).

Object:

An object is an instance of a class. It’s a concrete realization of the blueprint defined by the class. You can create multiple objects from the same class, each with its own set of property values.

<?php
// Creating objects from the Dog class
$dog1 = new Dog();
$dog2 = new Dog();

// Setting property values
$dog1->name = "Buddy";
$dog1->breed = "Labrador";

$dog2->name = "Max";
$dog2->breed = "Golden Retriever";

// Calling methods
$dog1->bark(); // Outputs: Woof! Woof!
$dog2->fetch(); // Outputs: Max is fetching.
?>

In this example, we’ve created two instances ($dog1 and $dog2) of the Dog class. Each object has its own set of properties and can invoke the methods defined in the class.

The Four pillars of OOPs are abstraction, encapsulation, inheritance, and polymorphism, We will discuss those concepts in details with real time example.

Abstraction:

Abstraction in object-oriented programming (OOP) refers to the concept of hiding the complex implementation details of an object and exposing only the essential features or functionalities. It allows you to focus on what an object does rather than how it achieves its functionality. In PHP, abstraction is achieved through abstract classes and interfaces.

Imagine you’re building a system to manage different shapes like circles, rectangles, and triangles. Each shape has an area, but the way you calculate the area for each shape is different.

Here’s an example in PHP:

// Abstract class representing a shape
abstract class Shape {
// Abstract method for calculating the area
abstract public function calculateArea();
}

class Circle extends Shape {
private $radius;

public function __construct($radius) {
$this->radius = $radius;
}

public function calculateArea() {
return pi() * pow($this->radius, 2);
}
}

class Rectangle extends Shape {
private $length;
private $width;

public function __construct($length, $width) {
$this->length = $length;
$this->width = $width;
}

public function calculateArea() {
return $this->length * $this->width;
}
}

$circle = new Circle(5);
$rectangle = new Rectangle(4, 6);

echo 'Circle Area: ' . $circle->calculateArea() . PHP_EOL;
echo 'Rectangle Area: ' . $rectangle->calculateArea() . PHP_EOL;

In this example, the Shape class is an abstract class that defines the common behavior for all shapes, which is the calculation of the area. The Circle and Rectangle classes are concrete classes that inherit from the Shape class and provide their specific implementations for calculating the area.

Encapsulation:

Encapsulation is one of the four fundamental principles, along with inheritance, polymorphism, and abstraction. Encapsulation refers to the bundling of data and the methods that operate on that data into a single unit, often called a class. The main idea is to hide the internal details of how an object works and expose only what is necessary for the outside world to interact with it.

Let’s use a simple real-time example

class Car {
// Private properties (attributes)
private $model;
private $color;
private $fuelLevel;

public function __construct($model, $color) {
$this->model = $model;
$this->color = $color;
$this->fuelLevel = 100;
}

// Public method to get the model of the car
public function getModel() {
return $this->model;
}

// Public method to get the color of the car
public function getColor() {
return $this->color;
}

// Public method to get the fuel level of the car
public function getFuelLevel() {
return $this->fuelLevel;
}

// Public method to simulate driving, reducing fuel level
public function drive() {
// Simulate driving by reducing fuel level
$this->fuelLevel -= 10;
if ($this->fuelLevel < 0) {
$this->fuelLevel = 0; // Ensure fuel level doesn't go below 0
}
}
}

$myCar = new Car("Toyota", "Blue");

echo "Model: " . $myCar->getModel() . "<br>";
echo "Color: " . $myCar->getColor() . "<br>";
echo "Fuel Level: " . $myCar->getFuelLevel() . "%<br>";

$myCar->drive();

echo "Updated Fuel Level after driving: " . $myCar->getFuelLevel() . "%";

In this example:

  • The Car class encapsulates the internal details (model, color, and fuel level) by declaring them as private properties.
  • The internal details are hidden from external code, and access is controlled through these public methods, providing a level of abstraction.

Inheritance:

Inheritance is a concept where a new class (called the child or subclass) can inherit attributes and behaviors (properties and methods) from an existing class (called the parent or superclass). This allows you to create a relationship between classes.

// Parent class
class Animal {
public $name;

public function __construct($name) {
$this->name = $name;
}

public function eat() {
return $this->name . ' is eating.';
}
}

// Child class inheriting from Animal
class Dog extends Animal {
public function bark() {
return $this->name . ' is barking.';
}
}

// Child class inheriting from Animal
class Cat extends Animal {
public function meow() {
return $this->name . ' is meowing.';
}
}

// Create instances of the classes
$dog = new Dog('Buddy');
$cat = new Cat('Whiskers');

// Using inherited methods
echo $dog->eat(); // Output: Buddy is eating.
echo $dog->bark(); // Output: Buddy is barking.

echo $cat->eat(); // Output: Whiskers is eating.
echo $cat->meow(); // Output: Whiskers is meowing.

In this example, we have a parent class Animal with a property $name and a method eat(). The Dog and Cat classes are child classes that inherit from the Animal class. They not only inherit the property and method from Animal but can also have their own unique methods (bark() for Dog and meow() for Cat).

By using inheritance, you avoid duplicating common code in each class and promote a more organized and reusable code structure.

Note:

If you want to learn about certain topics of Php, Laravel, Javascript, Mysql in detail, comment below and need some project ideas and tutorials feel free to comment below and subscribe to the newsletter for latest updates.

Thanks!

🤝🏻 Connect with Me on LinkedIn, Do also Follow on Twitter

--

--