Sobes.tech
Junior — Middle

How can you programmatically access private class fields without editing its source code?

sobes.tech AI

Answer from AI

In PHP, you can access private class fields using reflection (Reflection). This allows you to access properties and methods even if they are declared as private or protected, without modifying the class's source code.

Example:

class MyClass {
    private $secret = 'hidden';
}

$obj = new MyClass();

$reflection = new ReflectionClass($obj);
$property = $reflection->getProperty('secret');
$property->setAccessible(true); // make the private property accessible

echo $property->getValue($obj); // will output 'hidden'

Thus, using ReflectionProperty::setAccessible(true), you can access and modify private fields.