Magic Methods: Construction and Property Access

5.Magic Methods: Construction and Property Access

M

In this chapter

We'll learn PHP's magic methods — methods PHP calls by itself at special moments — starting with the ones for property access: __get(), __set(), __isset() and __unset(), which PHP's manual calls "overloading". We'll see where they're useful, how they hid a typo in a report, how __set() can forbid dynamic properties — and how Python's __getattr__, JavaScript's Proxy and C#'s indexers compare.

14–16 min

The Problem in Real Life

LegacyBooking is the oldest class in the project. It keeps all its data in one private array and uses a method called __get() so that $booking->status still works from outside. Olivia's weekly report says every booking is "pending".

Mia finds the report's line: if ($booking->stauts === "confirmed"). A typo — but there's no warning, no deprecation, nothing in the log. __get() received "stauts", didn't find it in the array, and quietly returned null.

M

A typo in a property name used to give a warning. Why did this one just return null?

Mia

Declared Properties vs. Properties Made Up at Runtime

Methods PHP calls for you

Magic methods start with __ and run automatically — on new, on a missing property, on a string conversion.

Typos disappear

__get() answers for ANY name, including misspelled ones. PHP and your tools can no longer tell a typo from a real property.

Or slam the door

The same mechanism can refuse unknown names loudly — one way to forbid dynamic properties.

Magic Methods: Construction and Property Access

Magic methods: methods whose names start with two underscores, like __construct(), are magic methods: you never call them yourself; PHP calls them at a particular moment. You know two already. This chapter covers the ones for property access:

  • __construct() and __destruct(): a quick recap (Act 11).
  • __get() and __set(): reading and writing properties that aren't accessible.
  • __isset() and __unset(): what isset() and unset() do on them.
  • Other languages: Python's __getattr__, JavaScript's Proxy, C#'s indexers.

The magic methods you know: __construct() runs on new and __destruct() when the last reference to an object is gone (Act 11), and __clone() runs on the copy after clone (Act 11). All magic methods follow the same idea: PHP has a fixed list of moments — creating, destroying, copying, reading an unknown property, calling an unknown method, converting to a string — and if a class has the matching method, PHP calls it at that moment. Names starting with __ are reserved for PHP, so never give your own methods such names.

__get() and __set(): when code reads a property that doesn't exist or isn't visible from where it's read, PHP calls __get($name) instead of warning, and returns what it returns. Writing such a property calls __set($name, $value). The PHP manual calls this overloading — not the Java kind (Act 11), but properties invented at runtime. It's how LegacyBooking stored everything in a private array, how Laravel's models expose database columns ($booking->status reads the row), and how lazy loading works: a proxy object loads its real data on the first __get(). The cost is what Mia found: __get() is called for every unknown name, typos included. PHP can't warn, because the class said "I handle unknown names", and your editor and PHPStan can't know which names are real. If your __get() returns null for unknown names, a typo becomes a silent wrong answer. The diagram below shows the decision PHP makes on every property read.

What PHP does on $obj->name

$booking->stauts

a property is read

1

Declared and visible here?

yes → return its value (no magic)

2: if not

Does the class have __get()?

yes → return __get("stauts") — whatever it decides

3: if not

Warning: Undefined property

and the value null

Mia's bug: __get() answers every name, typos included
<?php
class LegacyBooking
{
private array $data = ["customer" => "Clare Lefèvre", "status" => "confirmed"];
public function __get(string $name): mixed
{
return $this->data[$name] ?? null; // unknown names quietly become null
}
}
$booking = new LegacyBooking();
echo $booking->status, "\n"; // confirmed
if ($booking->stauts === "confirmed") { // typo: no warning, no deprecation
echo "counted\n";
} else {
echo "treated as pending\n"; // treated as pending
}

__isset() and __unset(): isset($booking->status) on an inaccessible property calls __isset($name), and unset() calls __unset($name). A class with __get() should always have __isset() too, or isset() and empty() give wrong answers: without it, isset($settings->currency) is false and empty() is true, even though __get() would return "GBP". (The ?? operator happens to work either way, because it falls back to __get().)

__get without __isset breaks isset() and empty()
<?php
class Settings // __get() only
{
private array $data = ["currency" => "GBP"];
public function __get(string $name): mixed
{
return $this->data[$name] ?? null;
}
}
class BetterSettings // __get() and __isset()
{
private array $data = ["currency" => "GBP"];
public function __get(string $name): mixed
{
return $this->data[$name] ?? null;
}
public function __isset(string $name): bool
{
return isset($this->data[$name]);
}
}
$plain = new Settings();
echo $plain->currency, "\n"; // GBP: __get() works...
var_dump(isset($plain->currency)); // bool(false): ...but isset() says it's not there
var_dump(empty($plain->currency)); // bool(true): and empty() says it's empty
$better = new BetterSettings();
var_dump(isset($better->currency)); // bool(true)
var_dump(empty($better->currency)); // bool(false)

Using magic safely: if you must use __get(), make it strict: look the name up in a fixed list, and throw an exception for anything else. Then typos fail loudly again. The same trick answers the question Act 11 left open — how to stop dynamic properties today rather than in PHP 9: a __set() that always throws makes writing any undeclared property an error. (readonly classes do it too, chapter 1, and chapter 7 shows the rest.) In new code, prefer declared properties, and property hooks (chapter 7) for computed values: everything magic can do for properties, hooks do with real, checkable property names.

Strict magic: unknown names fail loudly
<?php
declare(strict_types=1);
final class LegacyBooking
{
private const FIELDS = ["customer", "status"];
private array $data = ["customer" => "Clare Lefèvre", "status" => "confirmed"];
public function __get(string $name): mixed
{
if (!in_array($name, self::FIELDS, true)) {
throw new LogicException("LegacyBooking has no property '$name'");
}
return $this->data[$name];
}
public function __isset(string $name): bool
{
return in_array($name, self::FIELDS, true);
}
public function __set(string $name, mixed $value): void
{
throw new LogicException("Can't create property '$name'"); // no dynamic properties
}
}
$booking = new LegacyBooking();
foreach (["status", "stauts"] as $name) {
try {
echo $booking->$name, "\n";
} catch (LogicException $e) {
echo $e->getMessage(), "\n";
}
}
try {
$booking->note = "VIP";
} catch (LogicException $e) {
echo $e->getMessage(), "\n";
}
// confirmed
// LegacyBooking has no property 'stauts'
// Can't create property 'note'

Lazy objects (PHP 8.4): lazy loading used to be the classic reason for __get() magic: a proxy that loads its real data only when something is first read. PHP 8.4 builds that in. ReflectionClass::newLazyGhost() creates an object without running its constructor and gives it a function to call later; the first time any property is read or written, PHP runs that function to initialise the object, and from then on it's a completely normal object — no __get(), no proxy class, no typos hidden. Frameworks and database libraries use it to avoid loading data that's never used, like a report that's built but never shown. You'll rarely create lazy objects yourself, but you'll meet them inside Doctrine and Symfony.

A lazy ghost object (PHP 8.4)
<?php
declare(strict_types=1);
class DayReport
{
public array $bookings = [];
public function __construct()
{
echo "(loading 1,200 bookings)\n"; // the expensive part
$this->bookings = [1, 2, 3];
}
}
$class = new ReflectionClass(DayReport::class);
$report = $class->newLazyGhost(function (DayReport $object): void {
$object->__construct(); // runs only when first needed
});
echo "report created\n";
var_dump($class->isUninitializedLazyObject($report)); // bool(true): nothing loaded yet
echo count($report->bookings), " bookings\n"; // the first read triggers loading
var_dump($class->isUninitializedLazyObject($report)); // bool(false): now a normal object
// report created
// bool(true)
// (loading 1,200 bookings)
// 3 bookings
// bool(false)

Other languages: Python has the same idea with __getattr__ and __setattr__, and JavaScript with a Proxy object that intercepts every property access; both share PHP's trade-off between flexibility and checkability. C# has indexers — this[string key] — which make an object usable with square brackets. PHP has that too, but through an interface rather than a magic method: a class that implements ArrayAccess can be used as $settings["currency"]. The table below lists the property-related magic methods.

Table — Magic methods for objects and properties
MethodPHP calls it when…Typical use
__construct()new creates the objectMake the object complete and valid
__destruct()The last reference is goneRelease an outside resource
__clone()clone has copied the objectDeep-copy owned parts
__get($name)Reading an inaccessible propertyModels, proxies, lazy loading
__set($name, $value)Writing an inaccessible propertyModels; or throw to forbid dynamic properties
__isset($name)isset() or ?? on an inaccessible propertyAlways pair with __get()
__unset($name)unset() on an inaccessible propertyRemove from the internal store
C#-style indexers in PHP: ArrayAccess
<?php
declare(strict_types=1);
final class ShopSettings implements ArrayAccess
{
private array $values = ["currency" => "GBP", "slotMinutes" => 30];
public function offsetExists(mixed $key): bool { return isset($this->values[$key]); }
public function offsetGet(mixed $key): mixed { return $this->values[$key]; }
public function offsetSet(mixed $key, mixed $value): void { $this->values[$key] = $value; }
public function offsetUnset(mixed $key): void { unset($this->values[$key]); }
}
$settings = new ShopSettings();
echo $settings["currency"], " ", $settings["slotMinutes"], "\n"; // GBP 30
var_dump(isset($settings["tax"])); // bool(false)
Python: __getattr__ (the same idea)
# Python — called only when normal attribute lookup fails
class LegacyBooking:
def __init__(self):
self._data = {"status": "confirmed"}
def __getattr__(self, name):
if name in self._data:
return self._data[name]
raise AttributeError(name) # strict: typos fail loudly
b = LegacyBooking()
print(b.status) # confirmed
# b.stauts → AttributeError: stauts

Key Takeaway

Magic methods start with two underscores and are called by PHP at fixed moments. __get() and __set() run when code reads or writes a property that doesn't exist or isn't visible — PHP's "overloading". They power lazy loading and framework models, but they answer for every name, so a typo becomes null with no warning. Pair __get() with __isset(), keep them strict (throw for unknown names), and use a throwing __set() to forbid dynamic properties today. Python's __getattr__ and JavaScript's Proxy are the same idea; C#-style indexers are ArrayAccess in PHP.

Why This Matters

Magic property access is everywhere in older PHP code and in frameworks — Laravel models are built on it — so you need to recognise it. Knowing its price (typos that turn into silent nulls, tools that can't help) tells you when to use it, and how to make it strict when you do.

It also completes the dynamic-property story from Act 11: declared properties, readonly classes and a throwing __set() are three ways to make sure no object ever gets a property nobody planned.

LegacyBooking's __get() now throws for unknown names, and the report's typo failed on the first run. The other half of the legacy class is worse: an __call() method that forwards every method call to the SMS client. $notifier->sendSmss(...) — another typo — "works": no error, and no text is sent. That's the next chapter: magic methods for calls, strings, invoking and serialization.