Sobes.tech
Middle

What is reflection used for in PHP?

sobes.tech AI

Answer from AI

Reflection in PHP allows exploring and modifying the structure of code at runtime. This includes obtaining information about classes, objects, methods, properties, constants, and namespaces.

Main uses:

  • Introspection: Getting metadata about existing code (method names, arguments, access modifiers).
  • Dynamic creation of objects and method calls: Creating class instances and calling their methods by string name.
  • Framework and library development: Creating flexible systems capable of analyzing and interacting with user code (e.g., IoC containers, ORM).
  • Debugging and testing: Tools for analyzing code during execution.
  • Automatic documentation generation.

Example of obtaining class information using ReflectionClass:

<?php
// Getting information about the stdClass class
$reflectionClass = new ReflectionClass('stdClass');

echo $reflectionClass->getName(); // Outputs: stdClass

$methods = $reflectionClass->getMethods();
foreach ($methods as $method) {
    echo $method->getName() . "\n"; // Outputs method names (if any)
}

Example of dynamic method invocation:

<?php
class MyClass {
    public function myMethod($arg) {
        return "Hello, " . $arg;
    }
}

$className = 'MyClass';
$methodName = 'myMethod';
$argument = 'world';

$reflectionMethod = new ReflectionMethod($className, $methodName);
$object = new $className();

$result = $reflectionMethod->invoke($object, $argument);
echo $result; // Outputs: Hello, world