What is this __set_state that appears in var_export?

2

The var_export is used to export the data of a given value as a valid php code.

However, when I use it in an object of class stdClass , it returns me the following code:

stdClass::__set_state(array(
                 'one' => 1,
                 'two' => 1,
))

However, if I try to:

stdClass::__set_state(['one' => 1]);

It returns me

  

Call to undefined method stdClass :: __ set_state ()

And, in fact, it does not exist there.

  var_dump(method_exists($object, '__set_state')); // false

Where did this such as __set_state appear?

    
asked by anonymous 15.07.2015 / 17:35

1 answer

3

__set_state() is a function of the magic method group used by PHP in classes.

Basically any function that starts with __ is a magic function.

  

This static method is called for classes exported by var_export() since PHP 5.1.0 .

     

The only parameter of this method is an array containing exported properties in the array('property' => value, ...) form.

What translated:

  

This static method is called for classes exported by var_export() from PHP 5.1.0.

     

The only parameter for this method is an array containing properties exported in array('property' => value, ...) format.

Its correct use can be observed in the documentation:

class A
{
    public $var1;
    public $var2;

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

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

Where we can perform the assignment of the result of the var_export() function on the $a object% for object $b :

eval('$b = ' . var_export($a, true) . ';');

// Resultado do eval():
$b = A::__set_state(array(
    'var1' => 5,
    'var2' => 'foo',
));

And so get as output:

var_dump($b);

// Saída:
object(A)#2 (2) {
   ["var1"]=>
    int(5)
    ["var2"]=>
    string(3) "foo"
}
    
15.07.2015 / 17:59