php - reset/clear an object?

If your class has a constructor method which initialises everything, then you could just call that again to reset.


The accepted answer has a minor flaw which is that unsetting a property actually completely removes it from that object, so that a check like $this->someProperty == null would trigger an "Undefined property" notice. Properties are null by default, so this would be more correct:

class Object {
    function resetObject() {
        foreach ($this as $key => $value) {
            $this->$key = null;  //set to null instead of unsetting
        }
    }
}

There's also the possibility that some of the properties could have been given default values (e.g. protected $someArray = array();)...if you want to reset all the properties back to their original default values then you have to use reflection:

class Object {
    function resetObject() {
        $blankInstance = new static; //requires PHP 5.3+  for older versions you could do $blankInstance = new get_class($this);
        $reflBlankInstance = new \ReflectionClass($blankInstance);
        foreach ($reflBlankInstance->getProperties() as $prop) {
            $prop->setAccessible(true);
            $this->{$prop->name} = $prop->getValue($blankInstance);
        }
    }
}

That may be overkill but could be important in some scenarios. Note that this would fail if the class had required constructor arguments; in that case you could use ReflectionClass::newInstanceWithoutConstructor (introduced in PHP 5.4), then call __construct() manually after calling resetObject().


<?php  
function reset() {
    foreach (get_class_vars(get_class($this)) as $var => $def_val){
        $this->$var= $def_val;
    }
}
?>

class Object {
    function ResetObject() {
        foreach ($this as $key => $value) {
            unset($this->$key);
        }
    }
}

See: Object iteration

Tags:

Php