PHP
What is reflection?
Learn to query class and method info at runtime with the Reflection API.
What is reflection?
The Reflection API lets you query a class's method and property information at runtime. When you wrap a class with new ReflectionClass("UserService"), you can read its name, methods and properties.
Reflection is code that inspects code itself. Test frameworks, dependency containers and documentation generators are built on it.
This series introduces ReflectionClass, ReflectionMethod, ReflectionProperty and ReflectionFunction.
First step with ReflectionClass
ReflectionClass mirrors a class: once you build it, getName() returns the full name, getMethods() the method list and getProperties() the property list.
To inspect a class you first build an instance: $rc = new ReflectionClass("UserService");. The returned object drives method and property traversal.
For plain functions use ReflectionFunction; PHP's reflection family starts with these classes extending the abstract Reflection class.
Exercise Print the UserService class name
The UserService class is given. Build a ReflectionClass instance and print the class's full name with getName().
Show example solution
Build $rc = new ReflectionClass("UserService");. Then echo $rc->getName() . "\n"; to print it.
Example solution:
<?php
class UserService {
public function list(): array {
return [];
}
}
$rc = new ReflectionClass("UserService");
echo $rc->getName() . "\n";
Test yourself
-
When does reflection work?
- At compile time, while code is translated
- At runtime, while the program is already running
- Only in debugging mode
- Only while handling web requests
Show answer
At runtime, while the program is already running — Correct. Reflection queries class and method info while the program runs.
-
Complete the ReflectionClass call
<?php
$rc = new ____("UserService");
echo $rc->getName() . "\n";
Show answer
<?php
$rc = new ReflectionClass("UserService");
echo $rc->getName() . "\n";
-
Match the reflection family
- ReflectionClass
- Inspects a class
- ReflectionMethod
- Inspects a method
- ReflectionFunction
- Inspects a function
- ReflectionProperty
- Inspects a property
Next lesson: ReflectionClass