PHP Reflection API
PHP comes with a complete reflection API that adds the ability to reverse-engineer classes, interfaces, functions, methods and extensions. Additionally, the reflection API offers ways to retrieve doc comments for functions, classes and methods.
1. ReflectionClass
The ReflectionClass class reports information about a class.
class User {
public $username;
private $password;
public function __construct($username) {
$this->username = $username;
}
public function getUsername() {
return $this->username;
}
}
$reflector = new ReflectionClass('User');
echo $reflector->getName(); // Outputs: User
print_r($reflector->getProperties()); // Outputs array of ReflectionProperty objects
print_r($reflector->getMethods()); // Outputs array of ReflectionMethod objects
2. ReflectionMethod
The ReflectionMethod class reports information about a method.
$method = new ReflectionMethod('User', 'getUsername');
if ($method->isPublic()) {
echo "The method is public.";
}
3. Invoking Private Methods
Reflection can be used to bypass visibility modifiers (useful for testing).
$user = new User('JohnDoe');
$reflector = new ReflectionClass('User');
$property = $reflector->getProperty('password');
$property->setAccessible(true);
$property->setValue($user, 'secret123');
print_r($user);
4. Use Cases
- Dependency Injection Containers: Automatically instantiating classes and resolving their dependencies by inspecting constructor type hints.
- Automated Testing: Testing private methods or properties.
- Documentation Generators: Reading DocBlocks to generate API documentation.