Skip to Content
Course content

154: Reflection API in PHP

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're handed a mysterious electronic device. It has a few buttons and a screen, but no manual. To figure out how it works, you don't just start pressing buttons randomly; you take it to a specialist who has an X-ray machine. The X-ray doesn't change how the device functions, but it reveals the internal wiring, the hidden switches, and the exact layout of the circuitry that you can't see from the outside.

In PHP, the Reflection API is that X-ray machine. Usually, when we write code, we know exactly which class we're using and which method we're calling. But sometimes, you need your code to "look at itself." You need a way to ask PHP, "Hey, what methods does this object actually have?" or "Is this property private or public?" and "What arguments does this function expect?"

Interrogating a Class

Most of the time, you'll start with the ReflectionClass. This is the primary entry point for inspecting any class, interface, or trait. I've used this countless times when building custom frameworks or plugin systems where I didn't know which classes the user would write, but I knew I needed to find specific methods within them.

<?php
class UserProfile {
    public $username = 'DevGuru';
    protected $email = 'mentor@example.com';
    private $password = 'secret123';

    public function updateProfile($name, $email) {
        // Update logic here
    }
}

// Instead of using the object, we reflect on the class
$reflector = new ReflectionClass('UserProfile');

echo "Class Name: " . $reflector->getName() . "\n";
echo "Is it sealable? " . ($reflector->isFinal() ? 'Yes' : 'No') . "\n";

// Let's see what methods are available
$methods = $reflector->getMethods();
foreach ($methods as $method) {
    echo "Found method: " . $method->getName() . "\n";
}
?>

Notice that we aren't calling updateProfile(). We are asking the ReflectionClass to give us a list of ReflectionMethod objects. This allows us to analyze the metadata of the code without actually executing it yet.

The Secret Door: Accessing Private Members

Here is where things get a bit "dangerous." In a normal scenario, if you try to access a private property from outside a class, PHP will throw a fatal error. You're respecting the encapsulation. However, the Reflection API allows you to bypass this. I'll be honest: you should rarely do this in production application logic, but it is an absolute lifesaver for writing unit tests for legacy code that you can't easily refactor.

By using setAccessible(true), you can force PHP to let you see and modify private or protected properties.

<?php
$user = new UserProfile();
$reflector = new ReflectionClass($user);

// We want to see that private password
$property = $reflector->getProperty('password');

// Normally, this next line would crash the script
$property->setAccessible(true); 

echo "The hidden password is: " . $property->getValue($user);
?>

It's essentially a skeleton key. Use it sparingly, because if you rely on this too much, you're breaking the very principles of Object-Oriented Programming that keep your code maintainable.

When to actually use this

You might be thinking, "Why would I ever need this if I'm the one writing the classes?" The answer is automation. Think about how modern PHP frameworks work. When you define a route in a framework and it automatically injects the correct objects into your controller's constructor, that's Reflection at work. The framework is reflecting on your constructor, seeing that you asked for a DatabaseConnection object, and then creating that object for you.

Other common use cases include:

  • Auto-mapping: Converting a database row directly into a class object by matching column names to property names.
  • Custom Validation: Creating a system that looks for attributes or specific naming conventions (like methods starting with validate...) and runs them automatically.
  • Documentation Generators: Tools that scan your code to build a manual based on your docblocks and method signatures.

Just keep in mind that Reflection is slower than calling a method directly. It's an expensive operation because PHP has to do a lot of lookups in the background. If you're reflecting on a class inside a loop that runs 10,000 times, you're going to feel the performance hit.




📋 Practical Task

Build an Automated Event-Hook Runner

Your task is to create a "Plugin Runner" that executes all methods in a class that follow a specific naming convention. This simulates how many CMS systems handle "hooks" or "events."

Requirements:

  • Create a class named UserPlugin.
  • Inside UserPlugin, create three methods: onUserLogin(), onUserLogout(), and someOtherHelperMethod().
  • Write a script that uses ReflectionClass to inspect UserPlugin.
  • The script should loop through all methods and execute only those that start with the prefix onUser.
  • The method someOtherHelperMethod() must NOT be executed.

Expected Output: The script should trigger the logic inside onUserLogin and onUserLogout, but ignore the helper method.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.