R
Rishtaara
PHP Fundamentals
Lesson 20 of 32Article19 min

OOP — Introduction, Classes, Constructor & Destructor

Object-Oriented Programming bundles data (properties) and behavior (methods) into classes. Objects are instances of classes.

What is OOP?

Object-Oriented Programming bundles data (properties) and behavior (methods) into classes. Objects are instances of classes.

Real-life example: A class is a cookie cutter. Each cookie (object) has the same shape but different sprinkles (data).

  • Encapsulation — hide internal details
  • Inheritance — reuse parent class behavior
  • Polymorphism — same method, different classes
  • Abstraction — focus on what, not how

Classes and Objects

Define a class with class Name { }. Create objects with new Name(). Use -> to access properties and methods.

Real-life example: A Car class describes wheels and drive(). Your car object is the actual vehicle in the driveway.

Basic class
<?php
class Course {
  public string $title;
  public int $lessons;

  public function summary(): string {
    return "{$this->title} has {$this->lessons} lessons.";
  }
}

$php = new Course();
$php->title = "PHP Fundamentals";
$php->lessons = 32;
echo $php->summary();
?>

Constructor and Destructor

__construct() runs when an object is created. __destruct() runs when the object is destroyed — useful for closing files or connections.

Real-life example: Constructor is turning the key when you enter a room. Destructor is switching off lights when you leave.

Constructor / destructor
<?php
class User {
  public function __construct(
    private string $name,
    private string $email
  ) {
    echo "User created\n";
  }

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

  public function __destruct() {
    echo "User destroyed\n";
  }
}

$u = new User("Asha", "asha@example.com");
echo $u->getName();
?>