Why OOP? Classes and Objects

1.Why OOP? Classes and Objects

M

In this chapter

We'll learn why object-oriented programming exists, what a class and an object are, how new creates an object, how PHP's style of OOP compares with other languages — class-based, not everything an object, no inner or partial classes — and why a typo in a class property can't hide the way a typo in an array key can.

16–18 min

The Problem in Real Life

Sunday, 17 days before launch. The shop is closed, and Mia uses the quiet day to look at the whole project at once. src/ now holds 2,014 lines. A booking is an array with 14 keys, passed through 40 functions, and every function has to remember the exact spelling of every key.

Friday's last bug is still on her screen: one line in the cancellation code says $booking['stat'] = 'cancelled';. The booking was never cancelled. The array just got a fifteenth key called stat, and nothing — not PHP, not her editor — said a word.

Marcus draws three boxes on the whiteboard: Booking, Customer, Barber. "A booking isn't 14 loose values. It's a thing, with a shape and with rules. PHP can know about that shape — if we tell it."

M

Fourteen keys, forty functions. How is anyone supposed to keep all of that in their head?

Mia

Loose Arrays vs. Objects with a Shape

Nobody knows the shape

An array accepts any key. A misspelled key is just a new key — the data quietly goes wrong.

Data here, rules there

The booking is in one place and the rules about bookings are spread over 40 functions in many files.

A blueprint, many copies

Every booking has the same parts. Describe them once — a class — and build as many bookings as you need.

Why OOP? Classes and Objects

Object-oriented programming: so far, BookBay's code has been procedural: data in variables and arrays, and functions that work on it. Object-oriented programming (OOP) puts the data and the code that works on it together, in units called objects. This chapter covers the foundations:

  • Why OOP: what goes wrong when a program grows, and what objects change.
  • Classes and objects: the blueprint and the things built from it.
  • Creating objects: new, and how several objects live side by side.
  • PHP's kind of OOP: how it compares with JavaScript, Python, Java and C#, including the features PHP doesn't have.

Why OOP: procedural code is fine while a program is small. As it grows, two things hurt. First, data has no fixed shape: a booking array can have any keys, so a typo like stat creates a new key instead of an error. Second, data and rules drift apart: the rule "a cancelled booking can't be confirmed" lives in some function somewhere, and nothing stops other code from changing the array directly. OOP fixes both. You describe the shape once — "a booking has a customer, a start time and a status" — and you put the rules right next to the data, as functions that belong to it. Most modern languages use OOP, and almost all PHP frameworks, Laravel included, are built from it.

Mia's bug: an array accepts any key
<?php
$booking = ["customer" => "Clare Lefèvre", "status" => "confirmed"];
$booking["stat"] = "cancelled"; // a typo: just a new key, no message at all
echo $booking["status"], "\n"; // confirmed — the booking was never cancelled
echo count($booking), " keys\n"; // 3 keys

Classes and objects: a class is a blueprint: it describes what every booking has and can do. An object is one actual booking built from that blueprint — Clare's 9:30 haircut, say. One class, as many objects as you need, each with its own values. The values an object holds are called properties, and the functions that belong to it are called methods (chapter 2). You declare a class with class Booking { ... }; class names are written in PascalCase (every word capitalised), and in a real project each class gets its own file with the same name, like src/Booking.php (Act 13). The diagram below shows one blueprint and three objects built from it.

One class, many objects

class Booking

the blueprint: properties customer, status · method confirm()

new Booking() — three times

Clare's booking

customer: Clare Lefèvre · status: confirmed

Tom's booking

customer: Tom Hart · status: pending

Sam's booking

customer: Sam Ortiz · status: cancelled

independent

Each object has its own values

changing one booking never changes another

A class, and two objects built from it
<?php
class Booking
{
public string $customer = "";
public string $status = "pending";
}
$clare = new Booking(); // an object: an instance of Booking
$clare->customer = "Clare Lefèvre";
$tom = new Booking(); // a second, separate object
$tom->customer = "Tom Hart";
$tom->status = "confirmed";
echo $clare->customer, ": ", $clare->status, "\n"; // Clare Lefèvre: pending
echo $tom->customer, ": ", $tom->status, "\n"; // Tom Hart: confirmed

Creating objects with new: $booking = new Booking(); builds a new object from the class — this is called instantiation, and the object is an instance of the class. You reach its properties and methods with the arrow ->: $booking->status. Every new creates a separate object: changing one booking never changes another. var_dump() shows an object's class and properties, get_class($booking) gives its class name, and $booking instanceof Booking asks whether an object belongs to a class (Act 05). You've already met one object without writing a class: json_decode($json) without true gives you an object of PHP's built-in class stdClass, a plain bag of properties (Act 08).

Looking at objects: var_dump(), get_class(), instanceof
<?php
class Booking
{
public string $status = "pending";
}
$booking = new Booking();
var_dump($booking);
echo get_class($booking), "\n"; // Booking
var_dump($booking instanceof Booking); // bool(true)
$fromJson = json_decode('{"status": "confirmed"}');
echo get_class($fromJson), " ", $fromJson->status, "\n"; // stdClass confirmed
// object(Booking)#1 (1) {
// ["status"]=>
// string(7) "pending"
// }

A typo can't hide as easily: in a class, properties are declared: public string $status = "pending";. PHP now knows the shape. Reading a property that doesn't exist, like $booking->stat, gives a warning. Writing one creates a so-called dynamic property, and since PHP 8.2 that triggers a deprecation notice; the next major version of PHP will make it an error, and Act 12 shows how to switch it off today. Better still, your editor and tools like PHPStan (Act 21) know every class's properties and underline $booking->stat the moment you type it — something they can never do for an array key. That's the first thing objects give Mia: a shape that tools can check.

The same typo on an object: PHP speaks up
<?php
class Booking
{
public string $status = "confirmed";
}
$booking = new Booking();
$booking->stat = "cancelled"; // writing a property that isn't declared
echo $booking->status, "\n"; // confirmed
echo $booking->stauts, "\n"; // reading one that doesn't exist
// Deprecated: Creation of dynamic property Booking::$stat is deprecated
// confirmed
// Warning: Undefined property: Booking::$stauts

Class-based, not prototype-based: OOP comes in two main styles. In class-based languages — PHP, Java, C#, C++, Python — you write a class first, and objects are built from it. In prototype-based languages, the best known being JavaScript, there are no blueprints underneath: objects are created from other objects and inherit from them directly. (JavaScript added a class keyword in 2015, but it's a friendlier way to write prototypes.) PHP is purely class-based: every object has a class.

Not everything is an object in PHP: in Python and Ruby, everything is an object, even numbers and strings: Python's "Tom".upper() calls a method on a string. PHP is a hybrid: numbers, strings, booleans and arrays are plain values, not objects, so there's no "Tom"->upper(); you call functions like strtoupper("Tom") instead. Objects are only what you create from classes (and a few built-in classes like DateTime). This is one reason PHP has both thousands of functions and thousands of classes.

Python: everything is an object (not PHP)
# Python — strings and numbers are objects with methods
name = "tom"
print(name.upper()) # TOM
print((255).bit_length()) # 8
# PHP has no "tom"->upper(); strings are plain values:
# echo strtoupper("tom");

Class features PHP doesn't have: two class features from other languages are worth knowing by name. Nested (inner) classes, as in Java, let you declare a class inside another class, such as a Line class that only exists inside Invoice. PHP doesn't support nested classes: every class is declared at the top level of a file, and you group related classes with namespaces instead (Act 13). Partial classes, as in C#, let you split one class's code across several files that the compiler joins together. PHP doesn't support them either; the closest PHP tool is traits (chapter 9), which let several classes share pieces of code. The table below compares PHP's style of OOP with other languages.

Table — PHP's OOP compared with other languages
FeaturePHPOther languages
Objects are built fromClasses (class-based)JavaScript: other objects (prototypes)
Are numbers and strings objects?No: plain values with functionsPython, Ruby: yes, "Tom".upper()
Nested (inner) classesNot supported: use namespacesJava, C#: supported
Partial classes split over filesNot supported: traits share codeC#: supported
A plain bag of propertiesstdClassJavaScript: any object literal {}
Java: a nested class (not supported in PHP)
// Java — a class declared inside another class
public class Invoice {
private final java.util.List<Line> lines = new java.util.ArrayList<>();
public static class Line { // only makes sense as part of an Invoice
final String service;
final int pence;
Line(String service, int pence) { this.service = service; this.pence = pence; }
}
}
// In PHP, Line would be its own top-level class, e.g. BookBay\Invoice\Line (Act 13).

Key Takeaway

OOP keeps data and the rules about it together in objects. A class is the blueprint (properties for data, methods for behaviour); an object is one instance built with new, reached with ->. Declared properties give data a shape that PHP and your tools can check, unlike array keys. PHP's OOP is class-based (not prototype-based like JavaScript), and scalars and arrays are not objects (unlike Python and Ruby); PHP has no nested or partial classes.

Why This Matters

The bookings, customers and barbers in BookBay aren't loose values; they're things with parts and rules. Classes let the code say so, and once the code says so, PHP, your editor and your tools can check it — on every line, in every file.

Everything you'll do from here — Laravel's models, controllers, requests and jobs — is objects. Knowing exactly where PHP's OOP is like other languages and where it isn't also makes you faster at reading code and documentation written for Java, C# or Python.

Booking is now a class, and the stat typo is underlined in Mia's editor before she even saves. But her first Booking only holds data. When she adds the first piece of behaviour — a method that returns a one-line summary of the booking — PHP prints "Warning: Undefined variable $customer", although $customer is right there in the class. That's the next chapter: properties, methods and $this.