In this chapter
We'll learn the three visibility levels — public, protected and private — how they protect an object's data so that only its own methods can change it, why "private by default" is the rule, and the visibility levels other languages have that PHP doesn't: Java's package-private, C#'s internal and C++'s friend classes.
The Problem in Real Life
A Booking now starts complete. Then Mia searches the project for ->status = and finds it in eleven places. One line in the admin script sets $booking->status = "confirmd";. Another sets $booking->pricePence = -500; to "fix" a refund. A third confirms a booking that was already cancelled.
The rules exist — confirm() checks that a booking isn't cancelled — but nothing forces anyone to use them. Every property is open to every line of code.
There's a confirm() method with all the checks. Why can anyone just write the status directly?
Mia
Open to Everyone vs. Changed Only Through Methods
Anyone can write anything
A public property can be set from any file, to any value, skipping every rule the class has.
Private data, public methods
Hide the data and offer methods instead. The only way to change the status is through the rules.
Who counts as "inside"?
PHP has three levels. Java, C# and C++ have more — like package-private and friend classes.
Visibility: public, protected and private
Who may touch what: every property, method and constant in a class has a visibility that decides which code may use it. PHP has three levels:
- public: any code, anywhere.
- protected: the class itself and classes that inherit from it (chapter 7).
- private: only the class itself.
public, protected and private: public members can be used by any code: $booking->status from any file. private members can be used only by code inside the class — its own methods. From outside, $booking->status on a private property is an Error: "Cannot access private property Booking::$status". protected sits in between: the class and its child classes (chapter 7) may use it, outside code may not. Methods and constants have visibility too: a private method is a helper that only the class's own methods can call. If you leave the word out on a method, it's public. The diagram below shows the three levels as circles that grow outward.
Who can see a member — from the smallest circle to the largest
private
only code written inside Booking
protected
Booking + its child classes, e.g. GroupBooking
public
all code everywhere: other classes, functions, templates
<?phpclass Booking{public string $status = "pending";public int $pricePence = 2500;}$booking = new Booking();$booking->status = "confirmd"; // a typo, accepted$booking->pricePence = -500; // a negative price, acceptedecho $booking->status, " ", $booking->pricePence, "\n"; // confirmd -500
Private data, public methods: the fix for the eleven ->status = lines is to make the property private and offer methods for every allowed change: confirm(), cancel(), reschedule(). Each one checks its rule before changing anything, so "confirm a cancelled booking" and "status = confirmd" become impossible — there's no other door in. To let other code read a private value, add a small public method that returns it, called a getter: public function status(): string. This idea — an object guards its own data, and offers behaviour instead of raw fields — is called encapsulation, and chapter 10 comes back to it. Since PHP 8.4 there's also asymmetric visibility, public private(set) string $status, which makes a property readable by everyone but writable only inside the class; Act 12 covers it.
<?phpdeclare(strict_types=1);class Booking{private string $status = "pending";public function confirm(): void{if ($this->status === "cancelled") {throw new LogicException("A cancelled booking can't be confirmed"); // Act 14}$this->status = "confirmed";}public function cancel(): void{$this->status = "cancelled";}public function status(): string // a getter: read-only access{return $this->status;}}$booking = new Booking();$booking->confirm();echo $booking->status(), "\n"; // confirmedtry {$booking->status = "confirmd";} catch (Error $e) {echo $e->getMessage(), "\n"; // Cannot access private property Booking::$status}$booking->cancel();try {$booking->confirm();} catch (LogicException $e) {echo "Refused: ", $e->getMessage(), "\n"; // Refused: A cancelled booking can't be confirmed}
Private is per class, not per object: "private" means "only code written in this class", not "only this one object". So a Booking method may read the private properties of another Booking object — handy for comparing two bookings, as in the code below. Code in other classes, even classes that know bookings well, can't.
<?phpdeclare(strict_types=1);class Booking{public function __construct(private string $start, private int $barberId) {}public function clashesWith(Booking $other): bool{return $this->start === $other->start && $this->barberId === $other->barberId; // allowed}}$a = new Booking("09:30", 12);$b = new Booking("09:30", 12);var_dump($a->clashesWith($b)); // bool(true)try {echo $a->start;} catch (Error $e) {echo $e->getMessage(), "\n"; // Cannot access private property Booking::$start}
Start with private: make every property private (or protected, once inheritance needs it) unless there's a reason not to, and make public only the methods other code really needs. Public members are a promise: once other code uses them, changing them breaks that code. Private members can be renamed, retyped or removed without anyone outside noticing. In practice, value objects with readonly properties (chapter 6) are the main exception: when nobody can change them, there's nothing to protect, and public is fine.
Visibility in class diagrams (UML): design documents and interviews often show classes as UML class boxes: the class name on top, then the properties, then the methods, each with a symbol for its visibility — + for public, - for private, # for protected — and its type after a colon. Booking from this chapter would be drawn as below. Reading these boxes lets you understand a design at a glance, and drawing a few before you write code is a quick way to think about who should see what.
| Section | UML notation | In PHP |
|---|---|---|
| Class name | Booking | class Booking |
| Property | - status: string | private string $status |
| Property | # id: int | protected int $id |
| Method | + confirm(): void | public function confirm(): void |
| Method | + status(): string | public function status(): string |
| Static member | underlined name, e.g. + walkIn(): Booking | public static function walkIn(): static |
Visibility levels PHP doesn't have: other languages draw the line in more places. Java's default visibility, package-private, opens a member to every class in the same package (a folder of classes). C#'s internal opens it to the whole project (the "assembly"), and C# also has protected internal and private protected. C++ has friend classes: a class can name another class as its friend and let it see its private members. PHP doesn't support any of these: there are exactly three levels, and a namespace (Act 13) doesn't give any extra access. When PHP developers need "only my library may call this", they mark it @internal in a doc comment and let tools like PHPStan (Act 21) warn about it. The table below compares the levels.
| Level | The class itself | Child classes | Other code | In PHP? |
|---|---|---|---|---|
| public | Yes | Yes | Yes | Yes |
| protected | Yes | Yes | No | Yes |
| private | Yes | No | No | Yes |
| package-private (Java default) | Yes | Same package | Same package only | No |
| internal (C#) | Yes | Same project | Same project only | No: use @internal + PHPStan |
| friend (C++) | Yes | No | Only named friend classes | No |
// Java — no keyword means "package-private": visible to every class in the same packagepackage bookbay.booking;public class Booking {String status = "pending"; // other classes in bookbay.booking may read and write thisprivate int pricePence = 2500; // only Booking itself}// PHP has no equivalent: a property is public, protected or private, whatever namespace it's in.
Key Takeaway
public members are open to all code, protected to the class and its children, private to the class itself only. Keep data private and change it only through public methods that check the rules (encapsulation); add getters for reading. Private is per class, so a Booking method may read another Booking's private data. PHP has exactly three levels — no package-private (Java), internal (C#) or friend classes (C++); asymmetric visibility like private(set) arrived in PHP 8.4 (Act 12).
Why This Matters
Visibility is what turns the rules in your methods from suggestions into guarantees. With private data, there's exactly one way to confirm a booking — through confirm() — so the check in it can't be skipped, today or by someone writing new code next year.
It also keeps code changeable: everything private is yours to rename and rework, and only the public methods are a promise to the rest of the project. Every framework class you'll use is built this way.
The status is private, and the eleven direct writes are now calls to confirm() and cancel(). While moving shared values into the class, Mia adds a public static $currentCustomer to Booking, so every booking knows who's at the counter. Two walk-ins arrive at once — and the first booking suddenly shows the second customer's name. That's the next chapter: class constants and static members.
