PHP

PHP中怎么用反射API获取类信息

小亿
84
2024-04-29 16:09:46
栏目: 编程语言

在PHP中,可以使用反射API来获取类的信息。以下是一个简单的示例代码:

class MyClass {
    public $prop1;
    protected $prop2;
    private $prop3;

    public function method1() {
        // method code
    }

    protected function method2() {
        // method code
    }

    private function method3() {
        // method code
    }
}

$reflectionClass = new ReflectionClass('MyClass');

echo 'Class name: ' . $reflectionClass->getName() . "\n";

$properties = $reflectionClass->getProperties();
echo 'Properties: ';
foreach ($properties as $property) {
    echo $property->getName() . ', ';
}
echo "\n";

$methods = $reflectionClass->getMethods();
echo 'Methods: ';
foreach ($methods as $method) {
    echo $method->getName() . ', ';
}
echo "\n";

// 输出结果:
// Class name: MyClass
// Properties: prop1, prop2, prop3, 
// Methods: method1, method2, method3, 

在上面的示例中,首先创建了一个MyClass类。然后使用ReflectionClass来获取类的信息,包括类名、属性和方法。通过调用getName()方法获取类名,getProperties()方法获取属性列表,getMethods()方法获取方法列表。最后分别输出类名、属性和方法的信息。

0
看了该问题的人还看了