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
| Term | Means |
|---|---|
| Class | A blueprint — what the type knows and does. |
| Object / instance | A concrete value of that class. |
| Property | Data stored on an instance. |
| Method | A function defined on a class. |
| Constructor | Runs when you do new Class(...). |
$this | The 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 properties —
public 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
$ + four letters.
Discussion
Loading…