PHP Reflection API简介

哈Ha! 我向您介绍 Mustafa Magdi撰写的文章“ PHP Reflection API简介 ”的翻译。

如何在PHP中分析数据结构




参赛作品


当我开始用PHP编程时,我并不了解Reflection API的功能。 主要原因是我不需要设计简单的类,模块甚至包。 然后我发现这在许多领域都起着重要作用。 在本文中,我们将在以下几点考虑反射API

  1. 什么是反射API
  2. 安装与配置
  3. 使用方法
  4. 结论
  5. 推荐建议


1.什么是反射API


在计算机科学中, 反射反射 (内省的统称,英语反射)表示程序可以在运行时跟踪和修改其自身的结构和行为的过程。 - 维基百科
停止并查看代码内部内容( 逆向工程 )是什么意思? 让我们看下面的代码片段:

/** * Class Profile */ class Profile { /** * @return string */ public function getUserName(): string { return 'Foo'; } } 

Profile类是一个黑盒子。 使用Reflection API,您可以阅读其中的内容:

 //  $reflectionClass = new ReflectionClass('Profile'); //    var_dump($reflectionClass->getName()); => output: string(7) "Profile" //    var_dump($reflectionClass->getDocComment()); => output: string(24) "/** * Class Profile */" 

因此, ReflectionClass充当Profile类的分析师,这是Reflection API的主要思想。

PHP为您提供了任何锁定框的钥匙,因此我们拥有钥匙
对于以下内容:
ReflectionClass :报告班级信息。
ReflectionFunction :报告功能信息。
ReflectionParameter :检索有关函数或方法的参数的信息。
ReflectionClassConstant :报告类常量信息。

您可以在php.net上查看完整列表

2.安装和配置


要使用Reflection API类,无需安装或配置任何东西,因为它们是PHP核心的一部分。

3.使用实例


以下是一些如何使用Reflection API的示例:

范例1:
获取特定类的父类:

 //   class Child extends Profile { } $class = new ReflectionClass('Child'); //     print_r($class->getParentClass()); // ['Profile'] 

范例2:
获取getUserName()方法的文档:

 $method = new ReflectionMethod('Profile', 'getUserName'); var_dump($method->getDocComment()); => output: string(33) "/** * @return string */" 

范例3:
可以用作instanceOfis_a()来验证对象:

 $class = new ReflectionClass('Profile'); $obj = new Profile(); var_dump($class->isInstance($obj)); // bool(true) //    var_dump(is_a($obj, 'Profile')); // bool(true) //    var_dump($obj instanceof Profile); // bool(true) 

范例4:
在某些情况下,您可能会被单元测试所困扰,并想知道:“如何测试私有功能?!”

不用担心,这是窍门:

 //    getName() private function getName(): string { return 'Foo'; } $method = new ReflectionMethod('Profile', 'getUserName'); //          if ($method->isPrivate()) { $method->setAccessible(true); } echo $method->invoke(new Profile()); // Foo 

前面的示例非常简单,但是还有其他一些示例,您可以在其中看到Reflection API的用法更加广泛:
  • API文档生成器lavarel-apidoc-generator包大量使用了ReflectionClassReflrectionMethod来获取并随后处理有关类和方法的文档块的信息,并对这些代码块进行样式设置。
  • 依赖注入容器 :您可以在此处检查整个主题

4.结论


PHP提供了完整的反射API ,可帮助您轻松访问OOP结构的不同区域。

5.参考



来自翻译者:

您还可以在Stub类的Codeception包中看到一个使用Reflection API的示例。
通过反射的此类有助于在单元测试中浸入方法和属性。

应该补充的是,Reflection API的运行速度相当慢,因此您不应太参与其中。 建议在测试或调试期间使用它,但是如果可以不使用它,则最好这样做。 绝对不建议在项目的工作代码中使用它,因为 这也不安全。

Source: https://habr.com/ru/post/zh-CN433266/


All Articles