11. Object-Oriented PHP (OOP)

OOP in PHP helps you write modular, reusable, and maintainable code by organizing it into objects.


🔹 1. Classes & Objects

✅ Class

A class is a blueprint/template for creating objects.

class Car {
public $name; public function start() {
echo "Car started";
}
}

✅ Object

An object is an instance of a class.

$car1 = new Car();
$car1->name = "BMW";
$car1->start();

🔹 2. Properties & Methods

  • Properties → Variables inside a class
  • Methods → Functions inside a class
class Student {
public $name; public function showName() {
echo $this->name;
}
}

🔹 3. Constructor & Destructor

✅ Constructor (__construct)

Runs automatically when object is created

class User {
public function __construct() {
echo "Object Created";
}
}

✅ Destructor (__destruct)

Runs when object is destroyed

class User {
public function __destruct() {
echo "Object Destroyed";
}
}

🔹 4. Inheritance

Allows one class to inherit properties & methods from another class.

class Animal {
public function sound() {
echo "Animal sound";
}
}class Dog extends Animal {
public function bark() {
echo "Bark";
}
}

🔹 5. Encapsulation

Wrapping data and restricting access using access modifiers.

Access Modifiers:

  • public → accessible everywhere
  • private → only inside class
  • protected → class + inherited classes
class Bank {
private $balance = 1000; public function getBalance() {
return $this->balance;
}
}

🔹 6. Polymorphism

Same function name, different behavior.

class Animal {
public function sound() {
echo "Animal sound";
}
}class Cat extends Animal {
public function sound() {
echo "Meow";
}
}

🔹 7. Traits

Traits allow code reuse (like multiple inheritance workaround).

trait Logger {
public function log($msg) {
echo $msg;
}
}class User {
use Logger;
}

🔹 8. Interfaces & Abstract Classes

✅ Interface

Only method declarations (no body)

interface Payment {
public function pay($amount);
}

✅ Abstract Class

Can have both abstract and normal methods

abstract class Shape {
abstract public function area();
}

Example:

class Circle extends Shape {
public function area() {
return 3.14 * 10 * 10;
}
}

🚀 Pro Tips (Important for Students)

✔ Use OOP for large projects
✔ Follow SOLID principles (advanced)
✔ Practice with real examples:

  • User login system
  • Blog system
  • E-commerce cart