DEV Community

Carlos Viana
Carlos Viana

Posted on • Edited on

Object Oriented Programming in PHP

Object-Oriented Programming is a programming paradigm that organizes code around "objects," which are instances of "classes." These objects can have properties (data) and methods (functions) that define their behavior.

Classes
A class is like a "blueprint" or "template" that defines the characteristics and behaviors of an object. It describes the attributes (data) and methods (actions) that objects of that class will have.

Think of a class as the description of a type of object. It defines what the object can do (methods) and what the object has (properties/attributes), but it doesn't create the object itself.

Object
An object is an instance of a class. It is created from the class and represents an individual entity with defined attribute values and the ability to execute the methods specified in the class.

Think of an object as the concrete realization of a class. While the class is the plan, the object is the final product created from that plan.

Class and Object Example

<?php 

// Defining a class
class Car {
    // Properties
    public $color;
    public $model;

    // Method
    public function start() {
        return "The car is started!";
    }
}

// Creating an object
$myCar = new Car();

// Assigning the object's properties
$myCar->color = "Red";
$myCar->model = "Beetle";

// Using a method
echo $myCar->start(); // Output: The car is started!
Enter fullscreen mode Exit fullscreen mode

Inheritance
Inheritance is one of the core principles of Object-Oriented Programming (OOP), allowing a class to inherit properties and methods from another class. In simple terms, inheritance enables the creation of a new class (called a subclass or child class) that reuses, extends, or modifies the behavior of an existing class (called a superclass or parent class).

<?php 

// Parent class (superclass)
class Vehicle {
    public $brand;
    public $model;

    public function drive() {
        echo "The vehicle is being driven.";
    }
}

// Child class (subclass) that inherits from Vehicle
class Car extends Vehicle {
    public $numberOfDoors;

    // Method specific to the child class
    public function openDoor() {
        echo "Opening a car door.";
    }

    // Overriding a method from the parent class
    public function drive() {
        echo "The car is being driven.";
    }
}

// Creating an object of the child class Car
$myCar = new Car();
$myCar->brand = "Toyota";
$myCar->model = "Corolla";
$myCar->numberOfDoors = 4;

// Accessing methods from the parent and child classes
$myCar->drive();     // Outputs "The car is being driven."
$myCar->openDoor();  // Outputs "Opening a car door."
Enter fullscreen mode Exit fullscreen mode

Encapsulation
Encapsulation is the practice of hiding the internal details of an object and exposing only what is necessary for interacting with it. In other words, encapsulation allows you to control how an object's data is accessed and modified, protecting it from undue external interference.

This is achieved through access modifiers (like public, private, and protected) to determine which parts of an object can be accessed from outside the class.

  • public: Properties and methods can be accessed from anywhere.
  • private: Properties and methods can only be accessed within the class itself.
  • protected: Properties and methods can be accessed within the class and in subclasses.
<?php

class BankAccount {
    private $balance;

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

    // Public method for deposit
    public function deposit($amount) {
        if ($amount > 0) {
            $this->balance += $amount;
        }
    }

    // Public method to view balance
    public function getBalance() {
        return $this->balance;
    }

    // Private method, accessible only inside the class
    private function applyFee() {
        $this->balance -= 5; // Maintenance fee
    }
}

$account = new BankAccount(100);
$account->deposit(50);
echo $account->getBalance(); // Outputs 150
Enter fullscreen mode Exit fullscreen mode

Polymorphism
Polymorphism is one of the fundamental principles of Object-Oriented Programming (OOP) and refers to the ability of different classes to use methods with the same name but different behaviors. In other words, polymorphism allows the same method to be implemented in different ways in different classes.

The term "polymorphism" comes from Greek and means "many forms," indicating that a single method name can function differently depending on the object that invokes it.

<?php

// Parent class
class Animal {
    public function makeSound() {
        echo "The animal makes a sound.";
    }
}

// Child classes that override the makeSound method
class Dog extends Animal {
    public function makeSound() {
        echo "The dog barks.";
    }
}

class Cat extends Animal {
    public function makeSound() {
        echo "The cat meows.";
    }
}

// Function demonstrating polymorphism
function letAnimalMakeSound(Animal $animal) {
    $animal->makeSound();
}

// Creating objects of different classes
$dog = new Dog();
$cat = new Cat();

// Calling the method with polymorphic behavior
letAnimalMakeSound($dog);  // Outputs "The dog barks."
letAnimalMakeSound($cat);  // Outputs "The cat meows."
Enter fullscreen mode Exit fullscreen mode

You can run the code at https://onecompiler.com/php

Top comments (0)