What is this __set_state that appears in var_export?

Asked

Viewed 157 times

2

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

However, when I use it on a class object stdClass, it returns me the following code:

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

But if I try to do:

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

He returns to me

Call to Undefined method stdClass::__set_state()

And, in fact, it doesn’t exist there.

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

Where did this so-called __set_state?

1 answer

3


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

Basically any function starting 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 form array('property' => value, ...).

That translated:

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

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

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 execute the function result assignment var_export() in the object $a for the 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"
}
  • That is to say, var_export only serves to be used on objects if they implement them __set_state

  • @Wallacemaxters It is my understanding yes. But as I do not use much, there may be some other practical application for this "magic".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.