Returns the value of an object's attribute. This also works for attributes that are declared protected or private.
@since Method available since Release 3.4.0
object $object:
string $attributeName:
mixed
public static function getObjectAttribute($object, $attributeName) {
if (!is_object($object)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'object');
}
if (!is_string($attributeName)) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'string');
}
try {
$attribute = new ReflectionProperty($object, $attributeName);
} catch (ReflectionException $e) {
$reflector = new ReflectionObject($object);
while ($reflector = $reflector
->getParentClass()) {
try {
$attribute = $reflector
->getProperty($attributeName);
break;
} catch (ReflectionException $e) {
}
}
}
if (isset($attribute)) {
if (!$attribute || $attribute
->isPublic()) {
return $object->{$attributeName};
}
$attribute
->setAccessible(TRUE);
$value = $attribute
->getValue($object);
$attribute
->setAccessible(FALSE);
return $value;
}
throw new PHPUnit_Framework_Exception(sprintf('Attribute "%s" not found in object.', $attributeName));
}