Understanding PHP Reflection: Classes, Methods, Properties, and Annotations

This article explains PHP's reflection capabilities, detailing how developers can inspect classes, interfaces, methods, and properties at runtime, and demonstrates practical uses such as dynamic object creation, method invocation, property manipulation, and annotation parsing with code examples.

php Courses
php Courses
php Courses
Understanding PHP Reflection: Classes, Methods, Properties, and Annotations

PHP reflection 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 are difficult or impossible with static code analysis alone. PHP reflection has several uses, including:

Class and object analysis: retrieving information about classes, interfaces, methods, properties, and constants, useful for building generic libraries and tools.

Dynamic object creation: instantiating objects when the class name is stored in a string variable, valuable for configuration‑driven scenarios.

Method invocation and property access: dynamically calling methods and getting or setting property values even when their names are held in variables.

Annotation parsing: extracting and analyzing PHPDoc comments from classes and methods to attach metadata to code.

Key components of PHP reflection:

ReflectionClass

ReflectionClass

provides information about a class, including its name, parent class, interfaces, methods, properties, and constants.

<?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

handles class methods, allowing you to invoke them, retrieve parameter information, and access doc comments.

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.

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, storing metadata and additional information.

/**
 * @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 allows developers to use classes and objects in dynamic and creative ways. It is valuable for building flexible libraries, implementing dependency injection, automating testing, and other tasks.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

backend-developmentcode analysisReflectionPHPIntrospectionDynamic Instantiation
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.