Reset class instance variables using method

Does anyone know how to reset instance variables through a class method. Something like that:

class someClass 
{
    var $var1 = '';
    var $var2 = TRUE;

    function someMethod() 
    { 
        [...]
        // this method will alter the class variables
    }

    function reset()
    {
        // is it possible to reset all class variables from here?
    }
}

$test = new someClass();
$test->someMethod();
echo $test->var1;

$test->reset();
$test->someMethod();

I know that I can just do $ test2 = new SomeClass () BUT I am especially looking for a way to reset an instance (and its variables) using a method.

Is this even possible?

+3
source share
4 answers

You can use reflection to achieve this, for example using get_class_vars:

foreach (get_class_vars(get_class($this)) as $name => $default) 
  $this -> $name = $default;

This is not entirely safe, it breaks down into non-public variables (which it get_class_varsdoes not read), and it will not touch variables of the base class.

+5
source

Of course, the method itself can assign explicit values ​​to properties.

public function reset()
{
  $this->someString  = "original";
  $this->someInteger = 0;
}

$ this-> SetInitialState () from constructor

, , . .

<?php

  class MyClass {
    private $var;
    function __construct()     { $this->setInitialState(); }
    function setInitialState() { $this->var = "Hello World"; }
    function changeVar($val)   { $this->var = $val; }
    function showVar()         { print $this->var; }
  }

  $myObj = new MyClass();
  $myObj->showVar(); // Show default value
  $myObj->changeVar("New Value"); // Changes value
  $myObj->showVar(); // Shows new value
  $myObj->setInitialState(); // Restores default value
  $myObj->showVar(); // Shows restored value

?>
0

Yes, you could write reset () as:

function reset()
{
    $this->var1 = array();
    $this->var2 = TRUE;
}

You want to be careful because calling new someClass () will give you a completely new instance of a class that is completely unrelated to the original.

0
source

it's easy to do

public function reset()
{
    unset($this);
}
0
source

Source: https://habr.com/ru/post/1726291/


All Articles