Reset Class Variables At The Start Of A Loop

Do you have loads of variables that need resetting each time your code goes round a loop? Now you don't need to reset them one by one!

Resetting Class Variables

Often when looping, loads of variables need to be reset back to their default values at the start of the loop. Doing each one individually can be a pain for more than a few. Thankfully resetting class variables can be made much easier using get_class_vars, which returns an associative array containing the name of each variable together with its default value if any. It is then easy to loop through this array, resetting each variable to its default value.

If there is the odd variable that doesn't want to be reset eg a counter, this can be tested for and left alone.


class SomeClass
 private $variableOne = '';
 private $variableTwo = 0;
 private $array = ['fred', 'jim'];

 private function resetVars($noTouch)
   $class = get_class($this);
   $classVars = get_class_vars($class);
   foreach ($classVars as $name => $default) {
    if (!in_array($name, $noTouch)) {
     $this->$name = $default;

 public function goRoundLoop()
   foreach ($this->array as $value) {
    $this->variableOne .= ......