更准备的说是 如何用PHP分析类内部的结构。php
当我开始学习PHP编程时,可能并不知道 Reflection API
的强大功能,主要缘由是我不须要它来设计个人类,模块甚至是包等等,可是它在不少地方都有很是不错的能力。laravel
下面咱们来介绍 Reflection API
,主要是从这几个方面git
Reflection
是计算机程序在运行时检查,修改本身的结构和行为的能力 - 维基百科github
这是什么意思呢?让咱们来看下面的代码片断:编程
/** * Class Profile */ class Profile { /** * @return string */ public function getUserName(): string { return 'Foo'; } }
如今,Profile类是一个使用 ReflectionClass
的黑盒子,你能够获取它里面的内容:api
// 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
的主要思想。函数
除了上面用到的,其实还有更多,以下:单元测试
ReflectionClass:报告一个类的信息。 ReflectionFunction:报告有关函数的信息。 ReflectionParameter:检索有关函数或方法参数的信息。 ReflectionClassConstant:报告关于类常量的信息。学习
更多文档能够看这里 反射测试
Reflection API
是PHP内置的,不须要安装或配置,它已是核心的一部分。
在这里,咱们经过更多,来看如何使用 Reflection API:
// here we have the child class class Child extends Profile { } $class = new ReflectionClass('Child'); // here we get the list of all parents print_r($class->getParentClass()); // ['Profile']
getUserName()
函数注释$method = new ReflectionMethod('Profile', 'getUserName'); var_dump($method->getDocComment()); => output: string(33) "/** * @return string */"
instanceof
和 is_a()
同样来验证对象:$class = new ReflectionClass('Profile'); $obj = new Profile(); var_dump($class->isInstance($obj)); // bool(true) // same like var_dump(is_a($obj, 'Profile')); // bool(true) // same like var_dump($obj instanceof Profile); // bool(true)
// add getName() scope as private private function getName(): string { return 'Foo'; } $method = new ReflectionMethod('Profile', 'getUserName'); // check if it is private so we set it as accessible if ($method->isPrivate()) { $method->setAccessible(true); } echo $method->invoke(new Profile()); // Foo
前面的例子很是简单,下面是一些能够普遍查找Reflection API的地方:
文档生成器:laravel-apidoc-generator软件包,它普遍使用ReflectionClass
& ReflectionMethod
来获取关于类和方法的信息,而后处理它们,检出这个代码块。
依赖注入容器:下一篇来看。
PHP提供了一个丰富的反射API,使咱们能够更容易到达OOP结构的任何区域。
说白了就是在PHP运行时,能够经过反射深刻到类的内部,作咱们想作的事情。
关于更多PHP知识,能够前往 PHPCasts