How to set private property value of an object

30 May 2022 - nicolas

Here is a function that does the trick.

Also look for parent classes if the property is not in the current class.

The function

function setProperty($object, string $propertyName, $propertyValue, ReflectionClass $reflectionClass = null): void
{
    if (null === $reflectionClass) {
        $reflectionClass = new ReflectionClass($object);
    }

    try {
        $reflectionProperty = $reflectionClass->getProperty($propertyName);
    } catch (ReflectionException $exception) {
        // look inside parent class
        setProperty($object, $propertyName, $propertyValue, $reflectionClass->getParentClass());

        return;
    }

    $reflectionProperty = $reflectionClass->getProperty($propertyName);
    $reflectionProperty->setAccessible(true);
    $reflectionProperty->setValue($object, $propertyValue);
}

Usage

abstract class Fruit
{
    private string $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function getName(): string
    {
        return $this->name;
    }
}

class Apple extends Fruit
{
    public function __construct()
    {
        parent::__construct('apple');
    }
}

$apple = new Apple();
echo $apple->getName() . "\n"; // shows 'apple'

setProperty($apple, 'name', 'orange');
echo $apple->getName() . "\n"; // shows 'orange'