Properties, Methods and $this

2.Properties, Methods and $this

M

In this chapter

We'll learn how to declare typed properties and give them defaults, how methods work and how $this lets a method reach its own object, why a property that was never set is an error, how methods can be chained and how ?-> avoids errors on null — plus method overloading, a feature of Java and C# that PHP doesn't have, and what PHP offers instead.

15–17 min

The Problem in Real Life

Mia gives Booking its first method, summary(), which should return "Clare Lefèvre at 09:30 (confirmed)". Inside it she writes return "$customer at $start ($status)";.

PHP prints three warnings — "Undefined variable $customer", "$start", "$status" — and returns " at ()". The properties are right there, declared at the top of the class, a few lines above the method.

M

The method is inside the class, right below the properties. Why can't it see them?

Mia

Functions Next to the Data vs. Functions Inside It

A method is still a function

Like every function, a method can't see variables outside it — not even its own object's properties, unless it asks through $this.

Typed properties

A property can be typed like a parameter. PHP then refuses wrong values — and refuses to read a value that was never set.

Same name, different inputs?

In Java you can write two price() methods with different parameters. PHP has one method per name — and other tools for the same job.

Properties, Methods and $this

What objects are made of: an object has two kinds of members: properties, which hold its data, and methods, which are its functions. This chapter covers:

  • Properties: declaring them with types and defaults.
  • Methods and $this: how a method reaches its own object.
  • Calling methods: the arrow, chaining, and the nullsafe operator ?->.
  • Method overloading: what it is in other languages, and why PHP has none.

Properties: a property is declared inside the class with a visibility word (chapter 4 — for now, public), an optional type, a name and an optional default: public string $status = "pending";. Typed properties work like typed parameters (Act 09): with strict_types, putting an int into a string property is a TypeError. A typed property without a default starts uninitialized — it has no value at all, not even null — and reading it before something sets it is an Error: "must not be accessed before initialization". That's a feature: a booking whose customer was never set fails loudly instead of printing an empty name. Use ?string if "no value" is a real possibility, and set it to null explicitly.

Typed properties, and an uninitialized one
<?php
declare(strict_types=1);
class Booking
{
public string $customer; // no default: uninitialized
public string $status = "pending";
public ?string $note = null; // "no note" is allowed
}
$booking = new Booking();
echo $booking->status, "\n"; // pending
try {
echo $booking->customer;
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
// Typed property Booking::$customer must not be accessed before initialization

Methods and $this: a method is a function declared inside a class: public function summary(): string { ... }. It's called on an object — $booking->summary() — and inside it, the special variable $this means "the object this method was called on". Properties are reached through it: $this->customer. That was Mia's bug: a method is still a function, and a function can't see variables outside it (Act 09). $customer inside summary() was a new, undefined local variable. $this->customer is the object's property. Every method of every object uses $this the same way, so the one summary() method works for Clare's booking and Tom's. The diagram below shows what an object is made of, and where $this points.

What an object is made of

$booking

a variable pointing at one Booking object

the object holds

Properties: the data

customer · start · status

Methods: the behaviour

summary() · confirm() · cancel()

inside a method

$this inside summary()

= the same object summary() was called on → $this->customer

Mia's bug: $customer instead of $this->customer
<?php
class Booking
{
public string $customer = "Clare Lefèvre";
public string $start = "09:30";
public function summaryWrong(): string
{
return "$customer at $start"; // local variables that don't exist
}
public function summary(): string
{
return "{$this->customer} at {$this->start}"; // the object's properties
}
}
$booking = new Booking();
echo $booking->summaryWrong(), "\n";
echo $booking->summary(), "\n";
// Warning: Undefined variable $customer
// Warning: Undefined variable $start
// at
// Clare Lefèvre at 09:30

Methods change their object: a method can change its object's properties through $this — public function confirm(): void { $this->status = "confirmed"; } — and that change sticks, because $this is the object itself, not a copy. That's the big step from Act 08's arrays: instead of a function that receives a booking array and returns a changed copy, the booking knows how to confirm itself. The rules about bookings now live next to the booking's data, which is the whole point of OOP.

A method that changes its own object
<?php
declare(strict_types=1);
class Booking
{
public string $status = "pending";
public function confirm(): void
{
$this->status = "confirmed"; // changes this object, for good
}
}
$clare = new Booking();
$tom = new Booking();
$clare->confirm();
echo $clare->status, " ", $tom->status, "\n"; // confirmed pending

Chaining and the nullsafe operator: a method that returns $this (its own object) can be chained: $booking->confirm()->addNote("VIP")->summary() calls three methods in a row on the same object. Use it for builders and small setters, not for everything. When a value may be null — a booking may have no barber assigned yet — $booking->barber->name would fail on null. The nullsafe operator ?->, added in PHP 8.0, stops the chain and gives null instead: $booking->barber?->name ?? "any barber".

Chaining, and ?-> for values that may be null
<?php
declare(strict_types=1);
class Barber
{
public function __construct(public string $name) {} // chapter 3 explains this line
}
class Booking
{
public string $status = "pending";
public array $notes = [];
public ?Barber $barber = null;
public function confirm(): static
{
$this->status = "confirmed";
return $this; // return the object, so calls can chain
}
public function addNote(string $note): static
{
$this->notes[] = $note;
return $this;
}
}
$booking = (new Booking())->confirm()->addNote("VIP");
echo $booking->status, ", ", implode(",", $booking->notes), "\n"; // confirmed, VIP
echo $booking->barber?->name ?? "any barber", "\n"; // any barber
$booking->barber = new Barber("Ben");
echo $booking->barber?->name ?? "any barber", "\n"; // Ben

Method overloading — not in PHP: in Java and C#, a class can have several methods with the same name but different parameters, and the compiler picks the right one from the arguments: price(), price(int people), price(int people, boolean isHoliday). That's called method overloading. PHP doesn't support it: a class can have only one method per name, and declaring a second one is a fatal error, "Cannot redeclare Booking::price()". (Confusingly, the PHP manual uses the word "overloading" for something else — the magic methods __get() and __call(), Act 12.) PHP gets the same flexibility in other ways: default values and named arguments (Act 09), variadic parameters, union types, or simply different method names, which are often clearer anyway: price(), priceForGroup(). The table below sums up the parts of an object.

Table — Members of a class
MemberDeclared asUsed as
Typed property with a defaultpublic string $status = "pending";$booking->status
Typed property, no defaultpublic string $customer;Must be set before it's read
Nullable propertypublic ?Barber $barber = null;$booking->barber?->name
Methodpublic function summary(): string { ... }$booking->summary()
The object itself, inside a method$this$this->status
Chainable methodpublic function confirm(): static { ...; return $this; }$booking->confirm()->summary()
Method overloading in Java (not in PHP)
// Java — three methods with the same name; the compiler picks one by its arguments
class Booking {
int price() { return 2500; }
int price(int people) { return 2500 * people; }
int price(int people, boolean isHoliday) { return isHoliday ? price(people) * 110 / 100 : price(people); }
}
new Booking().price(); // 2500
new Booking().price(2); // 5000
new Booking().price(2, true); // 5500
PHP: one method, defaults and named arguments
<?php
declare(strict_types=1);
class Booking
{
public function price(int $people = 1, bool $isHoliday = false): int
{
$pence = 2500 * $people;
return $isHoliday ? intdiv($pence * 110, 100) : $pence;
}
}
$b = new Booking();
echo $b->price(), " ", $b->price(2), " ", $b->price(people: 2, isHoliday: true), "\n";
// 2500 5000 5500
// A second method called price() is not allowed:
// Fatal error: Cannot redeclare Booking::price()

Key Takeaway

Properties hold an object's data and can be typed; a typed property with no default is uninitialized until set, and reading it is an Error. Methods are functions inside the class; inside them, $this is the object the method was called on, and properties are reached as $this->name — a plain $name is just an undefined local variable. Methods can change their object, return $this for chaining, and ?-> stops safely at null. PHP has no method overloading (one method per name); use defaults, named arguments or separate names.

Why This Matters

$this is the single most used word in object-oriented PHP; every method that does anything uses it. Forgetting it is the classic first OOP bug, and knowing that a method is "a function with $this" makes the whole topic click: everything from Act 09 — parameters, types, return values, scope — still applies.

Typed properties are also what make objects safer than arrays: a booking can't quietly get a wrong type, and a booking whose customer was never set fails on the first read instead of sending "Hi ," to nobody.

summary() uses $this, and bookings now confirm themselves. But Mia notices something in the reminder log: "Hi , your booking at is confirmed." Somewhere, a Booking was created and used before anyone set its customer and start time — the class lets you build a half-finished booking. That's the next chapter: constructors.