简体   繁体   中英

php - reset/clear an object?

What I'm trying to do is use a temporary object to store values and then reset it back to empty without having to uset($tmpObject); ?

Here is some example code:

class Object {
    function ResetObject(){
        // code to remove all variables in an object here?
    }
}

$tmpObject = new Object();

foreach ($myArray as $arr){
    $tmpObject->val1 = "string1";
    $tmpObject->val2 = "string2";
    $tmpObject->val3 = "string3";
    $tmpObject->val4 = "string4";       
    $template->set('tmpObject',$tmpObject);
    $tmpObject->ResetObject();
}

Anyone have any ideas?

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

See: Object iteration

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 (eg 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;
    }
}
?>

Another way which combine unset and set with default value.

class Object {
    public function resetObject()
    {
        $clean = new self;
        foreach ($this as $key => $val){

            // If the attribute have a default value, use it 
            if (isset($clean->$key)){
                $this->$key = $clean->$key;
            }else{
                unset($this->$key);
            }
        }
    }
}

Reinitializing the variable will restore all object members to their preset values.

<?php

class Object {
  public $val1 = "val1";
  public $val2 = "val2";
}

$tmpObject = new Object();

$tmpObject->val1 = "string1";
$tmpObject->val2 = "string2";
$tmpObject->val3 = "string3";
$tmpObject->val4 = "string4";

var_dump($tmpObject);
$tmpObject = new Object();
var_dump($tmpObject);

?>

Outputs:

object(Object)#1 (4) {
  ["val1"]=>
  string(7) "string1"
  ["val2"]=>
  string(7) "string2"
  ["val3"]=>
  string(7) "string3"
  ["val4"]=>
  string(7) "string4"
}
object(Object)#2 (2) {
  ["val1"]=>
  string(4) "val1"
  ["val2"]=>
  string(4) "val2"
}

Instead of unset and even setting null, setting to default may be a better idea

class Foo {
public $bar = 'default bar';
private $baz = 'something';

  function __construct ()
  {
   /* assign whatever */
  }

 public function resetMe():Foo
 {
   $instance = new Foo();
   foreach($instance as $k => $v)
      $this->{$k} = $v;
 }
 return $this;
}

To use this

$foo = new Foo(); 
$foo->bar = 'set something different';
echo $foo->bar; // 'set something different'
$foo->resetMe();
echo $foo->bar; // 'default bar'

You can do this with reflection:

    private function resetPropertiesToDefault()
    {
        $blankInstance = $this->newInstance();
        $reflBlankInstance = new \ReflectionClass($blankInstance);
        foreach ($reflBlankInstance->getProperties() as $prop) {

            if ($prop->isStatic()) {
                continue;
            }

            $prop->setAccessible(true);

            $this->{$prop->name} = $prop->getValue($blankInstance);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM