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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php

class User{
 public $name;
 public $age;
 private $description;
 
 public function __construct($name,$age,$description){
        $this->name = $name;
        $this->age = $age;
        $this->description = $description;
    }
}

class About{
    public $name;
 public $age;
 
 public function __toString(){
        return "姓名:".$this->name.",年龄:".$this->age;
    }
}

$source = new User("Admin", 18, "test");
$aims = new About();
$sourceObject = new ReflectionObject($source);
 
foreach ($sourceObject->getProperties(ReflectionProperty::IS_PUBLIC) as $object) {
    foreach ($source as $key => $item) {
        if ($key != $object->getName()) {
   continue;
        }
        $object->setValue($aims,$item);
    }
}

echo $aims;

?>