Home  >  Article  >  Backend Development  >  Detailed explanation of __set_state() method in PHP

Detailed explanation of __set_state() method in PHP

藏色散人
藏色散人Original
2019-07-25 14:22:444641browse

__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=&#39;男&#39;)
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }
}
$person = new Person(&#39;小明&#39;); // 初始赋值
var_export($person);

See the results:

Person::__set_state(array( &#39;sex&#39; => &#39;男&#39;, &#39;name&#39; => &#39;小明&#39;, &#39;age&#39; => 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=&#39;男&#39;)
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }
    public static function __set_state($an_array)
    {
        $a = new Person();
        $a->name = $an_array[&#39;name&#39;];
        return $a;
    }
}
$person = new Person(&#39;小明&#39;); // 初始赋值
$person->name = &#39;小红&#39;;
var_export($person);

Continue reading Result:

Person::__set_state(array( &#39;sex&#39; => &#39;男&#39;, &#39;name&#39; => &#39;小红&#39;, &#39;age&#39; => 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn