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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1PHP's __get/__set fire only for inaccessible or undefined properties, letting you intercept all dynamic attribute access.
- 2Routing reads and writes through a backing array gives you a single place to enforce validation and guards.
- 3Implement __isset and __unset alongside __get/__set so isset() and unset() behave consistently on virtual properties.
Related explainers
php
<?php namespace App\Support;
Locale-aware formatting with PHP's intl extension
internationalization
encapsulation
constructor-injection
Intermediate
7 steps
php
<?php namespace App\Support;
Merging query params onto a URL in PHP
url-parsing
query-strings
immutability
Intermediate
8 steps
php
<?php class ImageUploadService {
Validating file uploads safely in PHP
file-upload
input-validation
security
Intermediate
8 steps
php
<?php namespace App\View;
Building a safe HTML escaper in PHP
security
xss
escaping
Intermediate
6 steps
php
<?php namespace App\Observers;
How Eloquent observers hook lifecycle events in Laravel
observers
lifecycle-hooks
queues
Intermediate
6 steps
php
<?php namespace App\Rules;
How a custom phone validation rule works in Laravel
validation
custom-rules
dependency
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/php-magic-methods-for-dynamic-attributes-explained-php-5297/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.