Last active
August 29, 2015 14:22
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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