6
6
7
7
class reflection {
8
8
9
+ /**
10
+ * Search for the class name that a property is defined in. This is useful
11
+ * as the reflection API uses that and not the class of the actual object.
12
+ *
13
+ * @param string $class_name The name of the starting class
14
+ * @param string $name The name of the thing to search for
15
+ * @param boolean $method If the thing being serched for is a method
16
+ *
17
+ * @return string The name of the owner class
18
+ */
19
+ private static function resolve_class (string $ class_name , string $ name , bool $ method ): string {
20
+ $ exists = ($ method ) ? 'method_exists ' : 'property_exists ' ;
21
+
22
+ do {
23
+ if ($ exists ($ class_name , $ name )) {
24
+ return $ class_name ;
25
+ }
26
+
27
+ $ class_name = get_parent_class ($ class_name );
28
+ } while ($ class_name !== false );
29
+
30
+ throw new \Exception ("Unable to find class for the property {$ property_name }" );
31
+ }
32
+
9
33
/**
10
34
* Gets the value of an object property
11
35
*
@@ -15,7 +39,8 @@ class reflection {
15
39
* @return mixed The value
16
40
*/
17
41
public static function get_property ($ object , string $ property_name ) {
18
- $ property = new \ReflectionProperty (get_class ($ object ), $ property_name );
42
+ $ class_name = static ::resolve_class (get_class ($ object ), $ property_name , false );
43
+ $ property = new \ReflectionProperty ($ class_name , $ property_name );
19
44
$ property ->setAccessible (true );
20
45
21
46
return $ property ->getValue ($ object );
@@ -31,7 +56,8 @@ public static function get_property($object, string $property_name) {
31
56
* @return void
32
57
*/
33
58
public static function set_property ($ object , string $ property_name , $ value ) {
34
- $ property = new \ReflectionProperty (get_class ($ object ), $ property_name );
59
+ $ class_name = static ::resolve_class (get_class ($ object ), $ property_name , false );
60
+ $ property = new \ReflectionProperty ($ class_name , $ property_name );
35
61
$ property ->setAccessible (true );
36
62
37
63
$ property ->setValue ($ object , $ value );
0 commit comments