ReflectionProperty
Learn a property's type and read private values with ReflectionProperty.
Inspect a property with ReflectionProperty
ReflectionProperty inspects a property. new ReflectionProperty("UserService", "apiKey") gives you the $apiKey property.
getType() returns the type, isStatic() whether it is static, isPrivate() whether it is private.
To read a private property you must call setAccessible(true); afterwards getValue($object) returns the value.
Using getValue and setValue
getValue($object) takes an object for non-static properties and returns the current value. setValue($object, $value) writes a new value.
For static properties pass null instead of an object: $rp->getValue(null).
Since PHP 8.1 setAccessible(true) is the default; writing it anyway makes intent clear and is required on older versions.
Exercise Read the private $apiKey value
The UserService class below has a private $apiKey property. Build a ReflectionProperty instance, call setAccessible(true) and print the value with getValue().
Show example solution
Build $rp = new ReflectionProperty("UserService", "apiKey");. Call $rp->setAccessible(true);. Print with echo $rp->getValue(new UserService()) . "\n";.
Example solution:
<?php
class UserService {
private string $apiKey = "sk_test_12345";
}
$rp = new ReflectionProperty("UserService", "apiKey");
$rp->setAccessible(true);
echo $rp->getValue(new UserService()) . "\n";
Test yourself
-
What is needed to read a private property?
- Just creating a ReflectionProperty
- Calling getValue() directly is enough
- Calling setAccessible(false)
- Calling setAccessible(true) first
Show answer
Calling setAccessible(true) first — Correct. setAccessible(true) opens private access; then getValue() works.
-
Complete the setAccessible call
<?php $rp = new ReflectionProperty("UserService", "apiKey"); $rp->____(true); echo $rp->getValue(new UserService()) . "\n";Show answer
<?php $rp = new ReflectionProperty("UserService", "apiKey"); $rp->setAccessible(true); echo $rp->getValue(new UserService()) . "\n"; -
Match ReflectionProperty methods
- getValue
- Reads the property value
- setValue
- Writes the property value
- setAccessible
- Opens private access
- getType
- Returns the property type