__set_state(), this static method will be called when calling var_export() to export a class.
Function:
Since PHP 5.1.0, this static method will be automatically called when var_export() is called to export a class.
Parameters:
The only parameter of this method is an array containing classes arranged in the format of array('property' => value, ...) Attributes.
Let’s first take a look at the code and running results without adding __set_state():
Code above:
<?php class Person { public $sex; public $name; public $age; public function __construct($name="", $age=25, $sex='男') { $this->name = $name; $this->age = $age; $this->sex = $sex; } } $person = new Person('小明'); // 初始赋值 var_export($person);
See the results:
Person::__set_state(array( 'sex' => '男', 'name' => '小明', 'age' => 25, ))
Obviously, all the attributes in the object are printed out
After adding __set_state():
Continue with the code:
<?php class Person { public $sex; public $name; public $age; public function __construct($name="", $age=25, $sex='男') { $this->name = $name; $this->age = $age; $this->sex = $sex; } public static function __set_state($an_array) { $a = new Person(); $a->name = $an_array['name']; return $a; } } $person = new Person('小明'); // 初始赋值 $person->name = '小红'; var_export($person);
Continue reading Result:
Person::__set_state(array( 'sex' => '男', 'name' => '小红', 'age' => 25, ))
The above is the detailed content of Detailed explanation of __set_state() method in PHP. For more information, please follow other related articles on the PHP Chinese website!