php 40 lines · 6 steps

PHP magic methods for dynamic attributes

An Entity class routes all property access through __get, __set, __isset, and __unset to store data in a guarded array.

Explained by highlit
1<?php
2 
3class Entity
4{
5 private array $attributes = [];
6 private array $guarded = ['id'];
7 
8 public function __construct(array $attributes = [])
9 {
10 foreach ($attributes as $key => $value) {
11 $this->$key = $value;
12 }
13 }
14 
15 public function __get(string $name): mixed
16 {
17 if (!array_key_exists($name, $this->attributes)) {
18 throw new \OutOfBoundsException("Undefined attribute: {$name}");
19 }
20 return $this->attributes[$name];
21 }
22 
23 public function __set(string $name, mixed $value): void
24 {
25 if (in_array($name, $this->guarded, true)) {
26 throw new \LogicException("Cannot set guarded attribute: {$name}");
27 }
28 $this->attributes[$name] = $value;
29 }
30 
31 public function __isset(string $name): bool
32 {
33 return isset($this->attributes[$name]);
34 }
35 
36 public function __unset(string $name): void
37 {
38 unset($this->attributes[$name]);
39 }
40}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1PHP's __get/__set fire only for inaccessible or undefined properties, letting you intercept all dynamic attribute access.
  2. 2Routing reads and writes through a backing array gives you a single place to enforce validation and guards.
  3. 3Implement __isset and __unset alongside __get/__set so isset() and unset() behave consistently on virtual properties.

Related explainers

Share this explainer

Here's the card — post it anywhere.

PHP magic methods for dynamic attributes — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code