QA
Intermediate LevelPHP 8+

How do PHP dunder magic methods (__get, __set, __call, __toString, __invoke) power dynamic object overloading?

❓ Interview Prompt: Explain PHP magic methods (__get, __set, __call, __callStatic, __toString, __invoke) and their role in Active Record ORMs.

PHP Magic Methods (prefixed with '__') intercept dynamic operations on objects:

Key Magic Methods:

•
'__get($prop)' / '__set($prop, $val)': Intercept access to inaccessible or undefined properties (powers ORM dynamic model attributes like '$user->email').
•
'__call($method, $args)': Intercepts calls to undefined instance methods (powers dynamic query builders like 'User::findByName()').
•
'__toString()': Controls string representation when an object is echoed ('echo $user').
•
'__invoke()': Allows an object instance to be called directly like a function ('$object()').

Code Implementation Example

php
<?php
class DynamicModel {
    private array $attributes = [];

    // Intercept property assignment: $model->name = "Alice"
    public function __set(string $name, mixed $value): void {
        $this->attributes[$name] = $value;
    }

    // Intercept property access: echo $model->name
    public function __get(string $name): mixed {
        return $this->attributes[$name] ?? null;
    }

    // Allow object to be invoked as a function: $model()
    public function __invoke(): array {
        return $this->attributes;
    }
}
💡Implementing dynamic property overloading and callable invocation using PHP magic methods.
🎯 Interview Key Takeaway

Magic methods (__get, __set, __call, __invoke) intercept dynamic property and method calls, powering ORMs and flexible APIs.

#Magic Methods#OOP#Overloading#Intermediate
Back to all PHP 8+ Questions→

More PHP 8+ Interview Questions

Beginner LevelPHP

What is PHP and how does its shared-nothing request lifecycle work?

Beginner LevelPHP

What is the difference between echo and print in PHP?

Beginner LevelPHP

What is the difference between isset(), empty(), and is_null() in PHP?