php反射机制
嘻嘻发布于2019-12-22
最后更新于2019年12月17日
浏览反射是对象能够检查自身,以在运行时获取其方法和属性。从表面上看,这似乎并没有什么用处。但是,反射实际上是软件开发中一个非常有趣的方面,您可能会经常涉及到它。
PHP反射一个例子:
/**
* Class Profile
*/
class Profile {
/**
* @return string
*/
public function getUserName(): string
{
return 'Foo';
}
}
现在,Profile类是一个黑匣子,使用ReflectionClass,您可以阅读其中的内容:
// instantiation
$reflectionClass = new ReflectionClass('Profile');
// get class name
var_dump($reflectionClass->getName());
=> output: string(7) "Profile"
// get class documentation
var_dump($reflectionClass->getDocComment());
=> output:
string(24) "/**
* Class Profile
*/"
因此,ReflectionClass就像我们的Profile类代理人一样,这是Reflection API的主要思想。
PHP反射能够让我们知道关于类的所有信息,具体如下:
ReflectionClass:类的信息。
ReflectionFunction:类函数的信息。
ReflectionParameter:检索有关函数或方法的参数的信息。
ReflectionClassConstant:报告有关类常量的信息。
PHP提供了丰富的Reflection API,能够很方便的访问OOP对象所有信息。