跳转到主内容
极星编程网:以代码为星,赴技术山海!

PHP Reflection API详解

PHP Reflection API是PHP5才有的新功能,它是用来导出或提取出关于类、方法、属性、参数等的详细信息,包括注释。

PHP Reflection API有:class Reflection { }interface Reflector { }class ReflectionException extends Exception { }class ReflectionFunction implements Reflector { }class ReflectionParameter implements Reflector { }class ReflectionMethod extends ReflectionFunction { }class ReflectionClass implements Reflector { }class ReflectionObject extends ReflectionClass { }class ReflectionProperty implements Reflector { }class ReflectionExtension implements Reflector { }

具体API说明:

①Reflection类②ReflectionException类该类继承标准类,没特殊方法和属性。

③ReflectionFunction类

④ReflectionParameter类:

⑤ReflectionClass类:getModifiers())进一步读取public bool isInstance(stdclass object)//测试传入的对象是否为该类的一个实例public stdclass newInstance(mixed* args)//创建该类实例public ReflectionClass getParentClass()//取得父类public bool isSubclassOf(ReflectionClass class)//测试传入的类是否为该类的父类public array getStaticProperties()//取得该类的所有静态属性public mixed getStaticPropertyValue(string name [, mixed default])//取得该类的静态属性值,若private,则不可访问public void setStaticPropertyValue(string name, mixed value)//设置该类的静态属性值,若private,则不可访问,有悖封装原则public array getDefaultProperties()//取得该类的属性信息,不含静态属性public bool isIterateable() public bool implementsInterface(string name)//测试是否实现了某个特定接口public ReflectionExtension getExtension() public string getExtensionName()}?>

⑥ReflectionMethod类:

⑦ReflectionProperty类:

⑧ReflectionExtension类

?>

使用例子:

public $age;

public function __construct(){$this->sex = "male";}

public function action(){echo "来自https://www.jb51.net的测试";}}

$class = new ReflectionClass('Person');//获取属性foreach($class->getProperties() as $property) {echo $property->getName()."\n";}//获取方法print_r($class->getMethods());

$p1 = new Person();$obj = new ReflectionObject($p1);

//获取对象和类的属性print_r($obj->getProperties());

很明显上面代码中对象和类获取的属性是不同的,这是因为对象进行了contruct实例化,因此多了sex属性,PHP Reflection确实能够获取很多有用的信息。

您可能感兴趣的文章:PHP反射类ReflectionClass和ReflectionObject的使用方法实例介绍PHP的Reflection反射机制PHP的反射类ReflectionClass、ReflectionMethod使用实例PHP中的reflection反射机制测试例子

相关文章