Sobes.tech
Middle+

Kus rakendub refleksioon PHP-s?

sobes.tech AI

Vastus AI-lt

Reflections in PHP are used in the following cases:

  • Studying the structure of classes and objects at runtime. This allows obtaining information about properties, methods, constants, annotations (in some implementations) of a class without needing to know its structure in advance.
  • Dynamic creation of objects and method calls. You can create class instances and call their methods using strings with class and method names.
  • Implementation of frameworks and libraries. Frameworks often use reflection for automatic processing of configurations, routing, dependency injection, and other aspects.
  • Testing. Reflection can be used to access private and protected properties/methods for testing purposes.
  • Serialization and deserialization of objects. Reflection can be used to automatically save and restore the state of objects.
  • Processing annotations (attributes). In PHP 8+, reflection is used to obtain information about attributes declared on classes, methods, properties, and functions.

Example of obtaining information about class methods:

<?php

class MyClass
{
    private $property;

    public function publicMethod(string $param): int
    {
        return 1;
    }

    protected function protectedMethod()
    {
        // ...
    }
}

$reflector = new \ReflectionClass(MyClass::class);
$methods = $reflector->getMethods();

foreach ($methods as $method) {
    echo "Method: " . $method->getName() . "\n";
    echo "Visibility: " . ($method->isPublic() ? 'public' : ($method->isProtected() ? 'protected' : 'private')) . "\n";
    // ... can get info about parameters, return type, etc.
}

Example of dynamic object creation and method invocation:

<?php

class AnotherClass
{
    public function greet(string $name): string
    {
        return "Hello, " . $name . "!";
    }
}

$className = 'AnotherClass';
$methodName = 'greet';
$paramValue = 'World';

$reflector = new \ReflectionClass($className);
$object = $reflector->newInstance();

$method = $reflector->getMethod($methodName);
$result = $method->invoke($object, $paramValue);

echo $result; // Outputs: Hello, World!