利用反射ReflectionClass类可以查看类的属性和方法。下面是一个示例:
class MyClass { public $property1 = 'value1'; private $property2 = 'value2'; public function method1() { echo 'This is method1'; } private function method2() { echo 'This is method2'; } } $reflectionClass = new ReflectionClass('MyClass'); // 获取类的所有属性 $properties = $reflectionClass->getProperties(); foreach ($properties as $property) { echo $property->getName() . "\n"; } // 获取类的所有方法 $methods = $reflectionClass->getMethods(); foreach ($methods as $method) { echo $method->getName() . "\n"; }
上面的代码首先创建了一个MyClass类,然后使用ReflectionClass类来获取该类的所有属性和方法。通过调用ReflectionClass的getProperties方法可以获取类的所有属性,并使用getName方法获取属性的名称。同样,通过调用getMethods方法可以获取类的所有方法,并使用getName方法获取方法的名称。
注意:ReflectionClass类可以获取公共、私有、受保护的属性和方法。如果要获取私有属性和方法,需要在调用getProperties和getMethods方法前先调用setAccessible(true)设置可访问性。