Author : beriba | 02/09/2014

Have you ever wondered is there any way to get private or protected properties from other object? Of course you have. If you’re developing something from scratch this is totally unneeded. You can just made a property either public or make get/set methods. Of course the second option is way much better.
But sometimes you are using a third-party module, you just can’t edit it and you need a private/protected property. In PHP it’s not the end of the world. Below you can find two methods, which sets and gets (respectively) non-public values.

/**
 * Sets value of protected or private property in given object
 *
 * @param mixed  $object   Object in which we want to change property value
 * @param string $property Property name
 * @param mixed  $value    New property value
 */
protected function setNonPublicValue($object, $property, $value)
{
    $reflectionObject = new ReflectionObject($object);
    $reflectionProperty = $reflectionObject->getProperty($property);
    $reflectionProperty->setAccessible(true);
    $reflectionProperty->setValue($object, $value);
}

/**
 * Gets value of protected or private property from given object
 *
 * @param mixed  $object   Object in which we want to change property value
 * @param string $property Property name
 *
 * @return mixed
 */
protected function getNonPublicValue($object, $property)
{
    $reflectionObject = new ReflectionObject($object);
    $reflectionProperty = $reflectionObject->getProperty($property);
    $reflectionProperty->setAccessible(true);

    return $reflectionProperty->getValue($object);
}

This is very dirty solution and should be used only when you’re aware what you’re doing and only when no other ways are possible.