Intermediate LevelPHP 8+
How does the PHP Reflection API inspect classes and power Dependency Injection Autowiring containers?
❓ Interview Prompt: Explain the PHP Reflection API (ReflectionClass, ReflectionMethod, ReflectionParameter), runtime metaprogramming, and DI container autowiring.
The Reflection API allows PHP to inspect class definitions, methods, properties, docblocks, and type hints at runtime.
How Reflection Powers DI Autowiring Containers:
When a framework container (Laravel Service Container, Symfony Container) needs to instantiate a controller or service:
1
It creates a 'ReflectionClass($className)' instance.
2
It inspects the constructor methods using '$reflection->getConstructor()'.
3
It iterates over constructor parameters using '$constructor->getParameters()', inspecting each parameter's type hint ('$param->getType()->getName()').
4
The container recursively resolves and instantiates those dependencies, auto-injecting them into the newly constructed class!
Code Implementation Example
php
<?php
class UserRepository {}
class UserService {
public function __construct(public UserRepository $repo) {}
}
// Simple Reflection DI Autowire Resolution
function autowire(string $class) {
$reflector = new ReflectionClass($class);
$constructor = $reflector->getConstructor();
if (!$constructor) return new $class();
$dependencies = [];
foreach ($constructor->getParameters() as $param) {
$type = $param->getType()->getName();
$dependencies[] = autowire($type); // Recursively resolve dependencies!
}
return $reflector->newInstanceArgs($dependencies);
}
$service = autowire(UserService::class); // Auto-injects UserRepository!💡Building a simple autowiring Dependency Injection container using PHP Reflection API.
🎯 Interview Key Takeaway
Dependency Injection containers use the Reflection API to inspect constructor type hints and automatically instantiate dependencies.
#Reflection#Dependency Injection#Metaprogramming#Intermediate
Back to all PHP 8+ Questions→