Reflection is generally defined as a program’s ability to inspect itself and modify its logic at execution time. In less technical terms, reflection is asking an object to tell you about its properties and methods, and altering those members (even private ones). In this lesson, we’ll dig into how this is accomplished, and when it might prove useful.
One of the most common ways in which reflection is useful is for debugging your code. You’ve probably used the get_class() and get_class_methods() functions when working with an ambiguously named object. The ability to get the type or methods of an object when you don’t know what type of object it is, is Reflection.
Another common use of Reflection is for creating documentation. It would be extremely labour intensive to write documentation about every method of every class of a large framework or application. Instead, Reflection can automatically generate the documentation for you. It does this by inspecting each method, constructor and class to determine what goes in and what comes out.
When should you use reflection:
- Dynamic typing is probably impossible without reflection
- Aspect Oriented Programming listens from method calls and places code around methods, all accomplished with reflection
- PHPUnit relies heavily on reflection, as do other mocking frameworks
- Web frameworks in general use reflection for different purposes. Some use it to initialize models, constructing objects for views and more
- Metaprogramming, like our last example, is hidden reflection
- Code analysis frameworks use reflection to understand your code
- When working with services or traits which can handle various kinds of objects