Object-Oriented PHP
Object-Oriented PHP
PHP supports classes, inheritance, and interfaces. OOP groups data and the methods that act on it into cohesive objects.
Classes and objects
class Product
{
public function __construct(
public readonly string $name,
public float $price
) {}
public function withTax(): float
{
return $this->price * 1.2;
}
}
$p = new Product('Keyboard', 79);
echo $p->withTax();
The constructor takes initial values, and properties are declared with visibility: public, protected, or private.
Inheritance
class Book extends Product
{
public function withTax(): float
{
return $this->price * 1.05;
}
}
Book inherits everything from Product and overrides the tax behavior. Inheritance works well for clear is-a relationships.
Interfaces
interface Payable
{
public function amount(): float;
}
An interface lists required methods without implementing them. Classes that implement it must provide the bodies, and code can type-hint against the interface instead of a concrete class.
Why OOP helps
Objects bundle related state and behavior, which reduces scattered globals. Type hints catch mistakes early, and inheritance or interfaces let you swap implementations, such as switching to a new provider, without touching the rest of the app.
When to use it
Simple pages can stay procedural, but as projects grow, grouping logic into classes and services keeps every piece testable and replaceable.
Key Points
- Classes define properties and methods for an object.
- Constructors set up initial state.
- public, protected, and private control access.
- Inheritance extends and overrides behavior.
- Interfaces define contracts for implementations.