Lab 06: Reflection API

Time: 40 minutes | Level: Advanced | Docker: docker run -it --rm php:8.3-cli bash

PHP's Reflection API allows introspecting classes, methods, properties, and attributes at runtime. This enables powerful patterns like dependency injection containers, ORMs, and serialization frameworks.


Step 1: ReflectionClass Basics

<?php
class UserService {
    public function __construct(
        private readonly string $name,
        private int $age = 30
    ) {}

    public function greet(): string { return 'Hello ' . $this->name; }

    #[\Deprecated('Use greet() instead')]
    public function hello(): string { return $this->greet(); }
}

$rc = new ReflectionClass(UserService::class);

echo "Class: "     . $rc->getName() . "\n";
echo "Short name: " . $rc->getShortName() . "\n";
echo "Abstract: "   . ($rc->isAbstract() ? 'yes' : 'no') . "\n";
echo "Final: "      . ($rc->isFinal() ? 'yes' : 'no') . "\n";

echo "\nMethods:\n";
foreach ($rc->getMethods() as $method) {
    $vis = $method->isPublic() ? 'public' : ($method->isProtected() ? 'protected' : 'private');
    echo "  $vis {$method->getName()}()\n";
}

📸 Verified Output:


Step 2: Inspecting Properties

📸 Verified Output:


Step 3: Invoking Methods via Reflection

📸 Verified Output:

💡 setAccessible(true) bypasses visibility — use only in test code or framework internals.


Step 4: Reading Attributes via Reflection

📸 Verified Output:


Step 5: Dynamic Proxy Pattern

📸 Verified Output:


Step 6: Reflection for Cloning & Deep Copy

📸 Verified Output:


Step 7: Constructor Parameter Inspection

📸 Verified Output:


Step 8: Capstone — Dependency Injection Container

📸 Verified Output:


Summary

Class
Key Methods
Use Case

ReflectionClass

getMethods(), getProperties(), getConstructor(), getAttributes()

Inspect class structure

ReflectionMethod

invoke(), getParameters(), setAccessible()

Dynamic method calls

ReflectionProperty

getValue(), setValue(), setAccessible(), isReadOnly()

Access private state

ReflectionParameter

getType(), isOptional(), getDefaultValue(), isPromoted()

Constructor analysis

ReflectionNamedType

getName(), isBuiltin(), allowsNull()

Type-based injection

DI Container

Reflection + recursion

Auto-wire constructor deps

Proxy Pattern

__call + ReflectionMethod

Transparent decoration

Last updated