Search code examples
phpmagic-methods

What is the real purpose of magic method __set_state in PHP?


I'm learning about magic methods, reading every site, taking every example, but nothing makes sense to me. Examples like this:

class A
{
    public $var1;
    public $var2;

    public static function __set_state($an_array) // As of PHP 5.1.0
    {
        $obj = new A;
        $obj->var1 = $an_array['var1'];
        $obj->var2 = $an_array['var2'];
        return $obj;
    }
}

$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';

eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
                                            //    'var1' => 5,
                                            //    'var2' => 'foo',
                                            // ));
var_dump($b);

What is the real purpose? Is for debugging or something?


Solution

  • __set_state is called in response to an instance of your object being passed to the var_export function.

    var_export Outputs or returns a parsable string representation of a variable.

    var_export takes an optional second parameter – a boolean that determines whether after the variable passed as the first argument is returned as a string instead of output.

    An example:

    class Dummy {
      private $value1_;
      private $value2_;
    
      function __construct() {
        $this->value1_ = 100;
        $this->value2_ = "100";
      }
    
      static function __set_state(array $array) {
        foreach($array as $k => $v) {
          echo("$k ==> $v <br/>");
        }
      }
    }
    $aDummy = new Dummy();
    //var_export by it self will output Dummy::__set_state(array( 'value1_' => 100, 'value2_' => '100', ))
    var_export($aDummy);
    eval(var_export($aDummy, true) . ';');
    

    Now the output is this:

    value1_ ==> 100

    value2_ ==> 100

    var_export can produce executable PHP code for the Dummy type with a __set_state method defined.

    var_export takes one argument, and it must be an array. It will contain key-value pairs of the properties or fields of the instance on which it is called.

    You can put anything you want in the __set_state method.