iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP OOP Intro

Object-oriented programming groups data and the functions that act on it into objects. PHP has been fully OOP-capable since version 5 — modern PHP (8.x) keeps adding sharpness.

Why OOP

  • Encapsulation — a class hides its internals behind a public API.
  • Inheritance — share behaviour between related classes.
  • Polymorphism — the same call works on different types.
  • Composition — build complex objects from simpler ones.

A minimal example

PHP
class Greeter {
    public function __construct(public string $name) {}

    public function hello(): string {
        return "Hello, {$this->name}!";
    }
}

$g = new Greeter('Ada');
echo $g->hello();   // Hello, Ada!

Vocabulary

TermMeans
ClassA blueprint — what the type knows and does.
Object / instanceA concrete value of that class.
PropertyData stored on an instance.
MethodA function defined on a class.
ConstructorRuns when you do new Class(...).
$thisThe current instance.
self:: / static::The class itself; static reference.

Modern PHP niceties

  • Constructor property promotion — declare and assign in one go: public function __construct(public string $name) {}.
  • Typed propertiespublic int $age;.
  • Readonly properties (8.1+)public readonly string $id;.
  • First-class enums (8.1+) — for a fixed set of cases.
Tip: OOP isn't always the right tool. For small scripts a function file is fine. The moment you have shared state and multiple verbs operating on it, a class earns its keep.

Example

Example
<?php
class Greeter {
    public function hello(): string {
        return 'Hello, world!';
    }
}
echo (new Greeter())->hello();
Try it Yourself »

Exercise

Reference the current instance with…

->name

Test yourself

Q1. "$this" refers to…
Q2. Encapsulation means…
Q3. Composition vs inheritance — modern advice is…

Discussion

Loading…