Introduction to PHP Reflection API

Hi, Habr! I present to your attention the translation of the article " Introduction to PHP Reflection API " by Mustafa Magdi .

How to analyze data structure in PHP


When I started programming in PHP, I did not know about the capabilities of the Reflection API . The main reason is that I did not need to design my simple classes, modules, or even packages. Then I discovered that it plays a major role in many areas. In the article we will discuss Reflection API on the following points:

  1. What is Reflection API
  2. Installation and configuration
  3. Using
  4. Conclusion
  5. Recommendations

1. What is Reflection API

In computer science, reflection or reflection (holonim introspection, English reflection) means a process during which a program can monitor and modify its own structure and behavior at run time. - Wikipedia .
What does the ability to stop and take a look inside your code ( reverse-engineering ) mean ? Let's look at the following code snippet:

 * Class Profile
    * @return string
    */publicfunctiongetUserName(): string{

The Profile class is a black box. Using the Reflection API you can read what is inside:

// инициализация
$reflectionClass = new ReflectionClass('Profile');
// получить имя класса
=> output: string(7) "Profile"// получить документацию класса
=> output:
string(24) "/**
 * Class Profile

Thus, ReflectionClass acts as an analyst for our Profile class , and this is the main idea of ​​the Reflection API .

PHP gives you the key to any locked box, so we have the keys
for the following:
ReflectionClass : reports class information.
ReflectionFunction : reports information about the function.
ReflectionParameter : retrieves information about the parameters of a function or method.
ReflectionClassConstant : reports information about a class constant.

You can learn a full list on

2. Installation and configuration

There is no need to install or configure anything to use the Reflection API classes , as they are part of the PHP core.

3. Examples of use

Below are some examples of how we can use the Reflection API :

Example 1:
Get the parent class for a particular class:

// дочерний классclassChildextendsProfile{
$class = new ReflectionClass('Child');
// получаем список всех родителей
print_r($class->getParentClass()); // ['Profile']

Example 2:
Get method documentation getUserName():

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

It can be used instanceOf, and is_a()for the validation object:

$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)

Example 4:
In some situations, you may be stuck with unit testing and ask yourself: “How can I test a private function ?!”

Don't worry, here’s a trick:

// добавим закрытый метод getName()privatefunctiongetName(): string{
$method = new ReflectionMethod('Profile', 'getUserName');
// проверим является ли метод закрытым и сделаем его доступнымif ($method->isPrivate()) {
echo $method->invoke(new Profile()); // Foo

The previous examples are fairly simple, but there are other examples in which you can see how the Reflection API is used more extensively:
  • API Documentation Generator : The lavarel-apidoc-generator package makes extensive use of ReflectionClass and ReflrectionMethod to receive and subsequently process information about the documentation of the classes and methods, and design these blocks of code.
  • Dependency Injection Container : check the whole topic here.

4. Conclusion

PHP provides a complete Reflection API that helps you easily reach different areas of OOP structures.

5. References

From the translator:

You can also see an example of using the Reflection API in the Codeception package in the Stub class .
This class through reflection helps us to wash methods and properties in unit tests.

It should be added that the Reflection API is quite slow, so you should not get carried away. It is recommended to use in tests or during debugging, but if you can do without it, then it is better to do so. And it is absolutely not recommended to use it in the working code of the project, since it's still not safe.

Also popular now: