🍉 加载中...


PHP反射实例:将现有对象属性值赋值给目标对象中对应属性

1 minute read
 1<?php
 2
 3class User{
 4 public $name;
 5 public $age;
 6 private $description;
 7 
 8 public function __construct($name,$age,$description){
 9        $this->name = $name;
10        $this->age = $age;
11        $this->description = $description;
12    }
13}
14
15class About{
16    public $name;
17 public $age;
18 
19 public function __toString(){
20        return "姓名:".$this->name.",年龄:".$this->age;
21    }
22}
23
24$source = new User("Admin", 18, "test");
25$aims = new About();
26$sourceObject = new ReflectionObject($source);
27 
28foreach ($sourceObject->getProperties(ReflectionProperty::IS_PUBLIC) as $object) {
29    foreach ($source as $key => $item) {
30        if ($key != $object->getName()) {
31   continue;
32        }
33        $object->setValue($aims,$item);
34    }
35}
36
37echo $aims;
38
39?>