What is the PHP Reflection API?
The PHP Reflection API is a built-in PHP feature that lets you inspect and retrieve metadata about classes, methods, properties, functions, and parameters at runtime. You can discover what arguments a constructor expects, which attributes are attached to a method, and much more — all without modifying the source code. Laravel relies heavily on the Reflection API insideIlluminate/Container/Container.php to power automatic dependency resolution, PHP attribute reading, and method injection.
Core classes
ReflectionClass — inspecting a class
ReflectionParameter — inspecting constructor arguments
The Laravel container and the Reflection API
Laravel’s IoC container uses the Reflection API to implement constructor injection — the automatic resolution of dependencies. Here is howapp()->make(SomeClass::class) and dependency injection work under the hood.
The container’s build() method (simplified)
The actual build() method in Container.php looks approximately like this.
Util::getParameterClassName() extracts the type name string from the result of $parameter->getType(). It wraps the ReflectionNamedType returned by ReflectionParameter::getType() into a convenient helper.Reading PHP attributes
Since PHP 8.0, the Reflection API lets you retrieve attributes attached to classes, methods, and properties. Laravel uses this mechanism to process queue attributes and Eloquent attributes.Basic pattern for reading attributes
How Laravel reads the Queue attribute (simplified)
Reading attributes on methods
Practical examples for package development
Checking whether a class implements an interface
Dynamically verify that a class implements a specific interface.Auto-registering routes from attributes
A pattern that combines attributes with Reflection to collect routes automatically.Method injection — calling with auto-resolved arguments
Laravel’scall() method uses Reflection to resolve arguments automatically. Here is a simplified implementation.
Collecting property default values
Retrieve the default values of a configuration class via Reflection.Performance considerations
The Reflection API parses class metadata every time it runs, so it carries a cost. Caching results is a best practice for production code.Next steps
PHP Attributes
Learn about PHP attributes that are read via ReflectionClass::getAttributes().
Package development
Learn how to build Laravel packages that leverage the Reflection API.