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

Detailed explanation of __set_state() method in PHP

藏色散人
Release: 2023-04-07 06:46:02
Original
4744 people have browsed it

__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);
Copy after login

See the results:

Person::__set_state(array( &#39;sex&#39; => &#39;男&#39;, &#39;name&#39; => &#39;小明&#39;, &#39;age&#39; => 25, ))
Copy after login

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);
Copy after login

Continue reading Result:

Person::__set_state(array( &#39;sex&#39; => &#39;男&#39;, &#39;name&#39; => &#39;小红&#39;, &#39;age&#39; => 25, ))
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template