PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
154: Reflection API in PHP
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(), andsomeOtherHelperMethod(). - Write a script that uses
ReflectionClassto inspectUserPlugin. - 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.
There are no comments for now.