CodeBlanks Logo Icon CodeBlanks

ReflectionProperty

PHP course · Expert · Lesson 18/54

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

  1. 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.

  2. 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";
    
  3. Match ReflectionProperty methods

    getValue
    Reads the property value
    setValue
    Writes the property value
    setAccessible
    Opens private access
    getType
    Returns the property type

All lessons in Expert