Skip to content

Instantly share code, notes, and snippets.

@holtkamp
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save holtkamp/f3a2ad32ca3866297c0f to your computer and use it in GitHub Desktop.
Save holtkamp/f3a2ad32ca3866297c0f to your computer and use it in GitHub Desktop.
Reset all (public, protected, private) properties of a class hierarchy in a bottom-up approach
<?php
/**
* Use reflection to reset all properties in the hierarchy of the current object.
*
* Because lower level classes, might define / override their own property values, we need to reset in the proper
* order: from parent to child
*
* @return void
*/
private function resetClassProperties()
{
$reflectionClass = new ReflectionClass($this);
$upstreamClasses = array($reflectionClass);
while ($parentReflectionClass = $reflectionClass->getParentClass()) {
$upstreamClasses[] = $parentReflectionClass;
$reflectionClass = $parentReflectionClass;
}
//Reverse the upstream sequence of all involved classes to get the proper downstream approach
$downstreamClasses = array_reverse($upstreamClasses);
foreach ($downstreamClasses as $reflectionClass) {
$this->resetReflectionClassProperties($reflectionClass);
}
}
/**
* @param ReflectionClass $reflectionClass
* @return void
*/
private function resetReflectionClassProperties(ReflectionClass $reflectionClass)
{
$classVariables = $reflectionClass->getDefaultProperties();
if (count($classVariables) > 0) {
foreach ($classVariables as $propertyName => $propertyValue) {
$reflectionProperty = $reflectionClass->getProperty($propertyName);
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($this, $propertyValue);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment