PHP – What is OOP?

Welcome to The Coding College! In this tutorial, we will dive into Object-Oriented Programming (OOP) in PHP. OOP is one of the most powerful programming paradigms and is widely used for designing scalable, reusable, and maintainable applications.

What is Object-Oriented Programming (OOP)?

Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to structure code. It is based on the concept of creating objects (real-world entities) that interact with each other to solve complex problems.

Key Concepts of OOP:

  1. Classes: Blueprints or templates for creating objects.
  2. Objects: Instances of a class that contain both data (properties) and behavior (methods).
  3. Encapsulation: Wrapping data and methods into a single unit and restricting access to certain components.
  4. Inheritance: Allowing a class to inherit properties and methods from another class.
  5. Polymorphism: The ability for different classes to be treated as instances of the same parent class.
  6. Abstraction: Hiding complex implementation details and exposing only the essential features.

Why Use OOP in PHP?

OOP makes your code:

  • Modular: Easy to break down into smaller components.
  • Reusable: Classes and objects can be reused across different projects.
  • Maintainable: Easier to update or modify code without affecting unrelated parts.
  • Scalable: Ideal for large-scale applications.

PHP supports OOP starting from PHP 5, making it a great choice for building modern, complex applications.

Understanding Classes and Objects

  • Class: A blueprint that defines the properties and methods of an object.
  • Object: A specific instance of a class.

Example: Defining a Class and Creating an Object

<?php
// Defining a Class
class Car {
    // Properties
    public $make;
    public $model;

    // Methods
    public function setMake($make) {
        $this->make = $make;
    }

    public function setModel($model) {
        $this->model = $model;
    }

    public function getCarInfo() {
        return "Make: " . $this->make . ", Model: " . $this->model;
    }
}

// Creating an Object
$myCar = new Car();
$myCar->setMake("Toyota");
$myCar->setModel("Corolla");
echo $myCar->getCarInfo();
// Output: Make: Toyota, Model: Corolla
?>

OOP Principles in PHP

1. Encapsulation

Encapsulation is about controlling access to the properties and methods of a class. PHP provides three access modifiers:

  • public: Accessible from anywhere.
  • protected: Accessible only within the class and its child classes.
  • private: Accessible only within the class.

Example:

<?php
class Person {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

$person = new Person();
$person->setName("John");
echo $person->getName(); // Output: John
?>

2. Inheritance

Inheritance allows one class to inherit the properties and methods of another class, promoting code reuse.

Example:

<?php
class Animal {
    public $name;

    public function makeSound() {
        return "Some sound";
    }
}

class Dog extends Animal {
    public function makeSound() {
        return "Bark";
    }
}

$dog = new Dog();
$dog->name = "Buddy";
echo $dog->name . " says " . $dog->makeSound();
// Output: Buddy says Bark
?>

3. Polymorphism

Polymorphism allows methods to have different implementations depending on the context, even with the same name.

Example:

<?php
class Shape {
    public function calculateArea() {
        return "Undefined";
    }
}

class Rectangle extends Shape {
    public function calculateArea($width, $height) {
        return $width * $height;
    }
}

$rectangle = new Rectangle();
echo "Area: " . $rectangle->calculateArea(10, 5);
// Output: Area: 50
?>

4. Abstraction

Abstraction is about hiding complex implementation details and exposing only essential features. In PHP, abstract classes and interfaces are used for abstraction.

Example: Abstract Class

<?php
abstract class Vehicle {
    abstract public function startEngine();
}

class Car extends Vehicle {
    public function startEngine() {
        return "Car engine started";
    }
}

$car = new Car();
echo $car->startEngine();
// Output: Car engine started
?>

Example: Interface

<?php
interface Logger {
    public function log($message);
}

class FileLogger implements Logger {
    public function log($message) {
        echo "Log to file: " . $message;
    }
}

$logger = new FileLogger();
$logger->log("Hello, OOP!");
// Output: Log to file: Hello, OOP!
?>

Real-World Example

Let’s create a simple E-commerce system with classes for Product and Cart.

<?php
class Product {
    public $name;
    public $price;

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

class Cart {
    private $items = [];

    public function addProduct(Product $product) {
        $this->items[] = $product;
    }

    public function getTotal() {
        $total = 0;
        foreach ($this->items as $item) {
            $total += $item->price;
        }
        return $total;
    }
}

// Create products
$product1 = new Product("Laptop", 1000);
$product2 = new Product("Mouse", 50);

// Add products to cart
$cart = new Cart();
$cart->addProduct($product1);
$cart->addProduct($product2);

// Display total
echo "Total: $" . $cart->getTotal();
// Output: Total: $1050
?>

Advantages of OOP in PHP

  1. Code Reusability: Create reusable classes and components.
  2. Modularity: Break down a large application into smaller, manageable parts.
  3. Scalability: Easily extend functionality through inheritance and polymorphism.
  4. Maintainability: Easier debugging and updates.

Conclusion

Object-Oriented Programming (OOP) is a powerful paradigm for building complex and scalable PHP applications. By mastering OOP concepts such as encapsulation, inheritance, polymorphism, and abstraction, you can write cleaner, more efficient, and reusable code.

For more detailed tutorials on PHP and programming, visit The Coding College.

Leave a Comment