What is OOP in PHP?

OOP (Object-Oriented Programming) in PHP is a programming style that allows you to structure your code around objects and classes rather than just functions and logic. It helps you build reusable, modular, and organized applications.

1. Core OOP Concepts in PHP

Concept Description
Class A blueprint for creating objects (e.g., Car, User)
Object An instance of a class
Property A variable inside a class
Method A function inside a class
Constructor A special method that runs when an object is created
Encapsulation Hides data using access modifiers
Inheritance A class can inherit properties/methods from another class
Polymorphism Same method behaves differently in different classes

2. Basic Class and Object Example


class Car {
    public $brand = "Toyota";

    public function honk() {
        return "Beep beep!";
    }
}

$myCar = new Car();
echo $myCar->brand;       // Output: Toyota
echo $myCar->honk();      // Output: Beep beep!

File: oop_basic.php

3. Constructor Example


class User {
    public $name;

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

    public function greet() {
        return "Hello, " . $this->name;
    }
}

$user = new User("Priya");
echo $user->greet(); // Output: Hello, Priya

File: constructor_example.php

4. Inheritance Example


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

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

$pet = new Dog();
echo $pet->makeSound(); // Output: Woof!

File: inheritance_example.php

5. Access Modifiers (Encapsulation)


class BankAccount {
    private $balance = 1000;

    public function getBalance() {
        return $this->balance;
    }
}

$acc = new BankAccount();
echo $acc->getBalance(); // Output: 1000

File: encapsulation_example.php

Summary Table

Feature Example File Purpose
Class & Object oop_basic.php Basics of object creation
Constructor constructor_example.php Set values when object is made
Inheritance inheritance_example.php Reuse parent class code
Encapsulation encapsulation_example.php Control access to data
Method Overriding inheritance_example.php Polymorphism