Understanding PHP Reflection: An In-Depth Guide with Examples
Tags: php, webdev, programming
Published: 2023-10-09 18:46:12

PHP Reflection is a powerful tool that allows you to analyze and manipulate class structures, interfaces, methods, properties, and more during runtime. 

It provides access to metadata about classes and objects, enabling various tasks such as dynamic object creation, method invocation, annotation analysis, and more.

## What is PHP Reflection?

Reflection in PHP refers to the ability to inspect and interact with the internal structure of classes, interfaces, methods, and properties at runtime. It enables developers to perform operations that would otherwise be challenging or impossible with static code analysis alone. PHP Reflection is used for various purposes, including:

1. **Class and Object Analysis:** Reflection allows you to retrieve information about classes, interfaces, methods, properties, and constants during runtime. This capability is useful for creating universal libraries and tools that work with diverse classes and objects.

2. **Dynamic Object Creation:** You can dynamically create objects of classes, even when the class name is stored in a string variable. This dynamic object creation is particularly valuable for scenarios like creating instances based on configuration data.

3. **Method Invocation and Property Access:** Reflection enables the dynamic invocation of methods and the retrieval or modification of property values, even when their names are stored in variables.

4. **Annotation Parsing:** You can extract and analyze PHPDoc annotations from class and method doc comments, allowing you to add metadata to your code.

## Key Components of PHP Reflection

**ReflectionClass:**
`ReflectionClass` provides information about classes, including their names, parent classes, interfaces, methods, properties, and constants.

```php
<?php

class ParentClass {}
interface MyInterface {}

class MyClass extends ParentClass implements MyInterface {}

$reflectionClass = new ReflectionClass('MyClass');

echo $reflectionClass->getName(); // Outputs "MyClass"

$parentClass = $reflectionClass->getParentClass();
if ($parentClass) {
    echo $parentClass->getName(); // Outputs "ParentClass"
}

$interfaces = $reflectionClass->getInterfaces();
foreach ($interfaces as $interface) {
    echo $interface->getName(); // Outputs "MyInterface"
}
```

**ReflectionMethod:**
`ReflectionMethod` is used to work with methods of a class. You can call methods, retrieve information about their parameters, and access annotations.

```php
class Math {
    public function add($a, $b) {
        return $a + $b;
    }
}

$reflectionClass = new ReflectionClass('Math');
$reflectionMethod = $reflectionClass->getMethod('add');

$object = $reflectionClass->newInstance();
$result = $reflectionMethod->invoke($object, 16, 26);
echo $result; // Outputs "42" - The Ultimate Question of Life, the Universe, and Everything

$parameters = $reflectionMethod->getParameters();
foreach ($parameters as $parameter) {
    echo $parameter->getName(); // Outputs "a" and "b"
}
```

**ReflectionProperty:**
`ReflectionProperty` provides information about class properties and allows you to get or set their values.

```php
class Person {
    public $name = 'Nick';
}

$reflectionClass = new ReflectionClass('Person');
$reflectionProperty = $reflectionClass->getProperty('name');

$object = $reflectionClass->newInstance();
$reflectionProperty->setValue($object, 'Natalia');
echo $reflectionProperty->getValue($object); // Outputs "Natalia"
```

**ReflectionAnnotation:**
Reflection can also be used to parse annotations (PHPDoc) from class and method doc comments. Annotations can store metadata and additional information about your code.

```php
/**
 * @Author("Nick G.")
 * @Description("This is a sample class")
 */
class SampleClass {}

$reflectionClass = new ReflectionClass('SampleClass');
$docComment = $reflectionClass->getDocComment();
echo $docComment; // Outputs class annotations
```

PHP Reflection is a versatile tool that empowers developers to work with classes and objects in dynamic and creative ways. It is invaluable for tasks such as building flexible libraries, implementing dependency injection, conducting automated testing, and much more. 

Understanding and harnessing the power of Reflection in PHP can elevate the quality and flexibility of your PHP applications.