PHP 反射机制打印对象

发布时间 2023-05-26 14:53:58作者: 心随所遇
 1 <?php
 2 /**
 3 
 4 echo Obj::new('Redis');
 5 echo Obj::new('Redis')->method('set')?->isPublic();
 6 
 7  */
 8 
 9 class Obj extends ReflectionClass
10 {
11     public static function std(?array $attrs = null)
12     {
13         $std = new \stdClass();
14         foreach ($attrs as $key => $value) {
15             is_numeric($key) ? $std->$value = '' : $std->$key = $value;
16         }
17         return $std;
18     }
19 
20     public static function new($argument)
21     {
22         return new static($argument);
23     }
24 
25     public function constant($name)
26     {
27         return $this->getConstant($name);
28     }
29 
30     public function property($name)
31     {
32         try {
33             return $this->getProperty($name);
34         } catch (\ReflectionException $e) {
35             return null;
36         }
37     }
38 
39     public function method($name)
40     {
41         try {
42             return $this->getMethod($name);
43         } catch (\ReflectionException $e) {
44             return null;
45         }
46     }
47 
48 
49     public function __toString()
50     {
51         $items = $this->getReflectionConstants();
52         foreach ($items as $key => $item) {
53             $class['const'][] = sprintf('const %s = %s;', $item->getName(), $item->getValue());
54         }
55 
56         $items = $this->getProperties();
57         foreach ($items as $key => $item) {
58             $class['prop'][] = sprintf('%s %s = "%s"', implode(' ', Reflection::getModifierNames($item->getModifiers())), $item->getName(), $item->getDefaultValue());
59         }
60 
61         $items = $this->getMethods();
62         foreach ($items as $key => $item) {
63             $params = $item->getParameters();
64             $param = '';
65             if ($params) {
66                 foreach ($params as $item1) {
67                     $param .= $item1->getType() . ' ' . $item1->getName();
68                     if ($item1->isDefaultValueAvailable()) {
69                         $param .= '=' . $item1->getDefaultValue() . ', ';
70                     } else {
71                         $param .= ', ';
72                     }
73                 }
74                 $param = rtrim($param, ', ');
75             }
76 
77             $class['method'][] = sprintf('%s %s(%s )', implode(' ', Reflection::getModifierNames($item->getModifiers())), $item->name, $param);
78         }
79 
80         $output = array_merge($class['const'] ?? [], $class['prop'] ?? [], $class['method'] ?? []);
81 
82         return implode("\n", $output);
83     }
84 }