PHP魔术方法__set_state()

2018-09-18 11:00 By "Powerless" 2920 0 1

__set_state()方法的参数是个数组,包含所有属性的值,格式为array('property' => value, ...)。

示例代码如下:

<?php
class Person
{
    public $sex;
    public $name;
    public $age;
    public function __construct($name="",  $age=25, $sex='Male')
    {
        $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('John'); // 赋初始值
$person->name = 'Jams';
var_export($person);

输出结果如下:

Person::__set_state(array( 'sex' => 'Male', 'name' => 'Jams', 'age' => 25, ))

如果类中没有定义__set_state()会怎样?我们来试试看。

<?php
class Person
{
    public $sex;
    public $name;
    public $age;
    public function __construct($name="",  $age=25, $sex='Male')
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }
}
$person = new Person('John'); // 赋初始值
var_export($person);

输出结果如下:

Person::__set_state(array( 'sex' => 'Male', 'name' => 'John', 'age' => 25, ))

可见,输出结果是对象的属性。


评 论

View in WeChat

Others Discussion

  • MySQL中的行级锁,表级锁,页级锁
    Posted on 2018-08-25 11:00
  • MySQL分组
    Posted on 2019-11-18 14:00
  • PHP练习-爬楼梯问题
    Posted on 2020-08-14 23:56
  • PHP8.1 性能基准测试
    Posted on 2022-10-08 17:40
  • MySQL事务介绍
    Posted on 2019-06-05 18:14
  • 必学十大经典排序算法,看这篇就够了
    Posted on 2019-11-18 16:30
  • 巧用CAS解决数据一致性问题
    Posted on 2019-03-07 11:55
  • PHP练习-无重复字符的最长子串
    Posted on 2020-09-17 18:03