PHP Reflection

Beginning work on the Analyze PHP framework, specifically the container, brought reflection to my awareness. Before that I had maybe heard the term, but I definitely hadn’t used it intentionally. Although it sounds like a scary computer science concept, it’s not. It’s actually quite simple:

Reflection is the ability of a computer program to examine, introspect, and modify its own structure…

That’s it. (Thanks, Wikipedia)

Reflection in PHP

PHP provides a complete reflection API and multiple functions right out of the box. This provides an object the ability to examine itself and report back things like its methods and properties. With that functionality, we can automatically create documentation, inject dependencies, and a lot more.

It’s possible that you have used reflection and didn’t realize it. If you’ve ever used the get_class()  or method_exists()  functions, you’ve used reflection.

Examples of PHP Reflection

Here’s the class we’ll be working with:

To start off, let’s use some of PHP’s built in functions to print out information about the class. First, we’ll print out the class methods.

Next, let’s just get the name of the class.

As I mentioned above, PHP provides a complete API. The PHP Reflection class provides us with a lot of powerful tools to inspect our objects. Using the class is simple, just instantiate the class passing along the object you’d like to inspect. Like so:

Now you can get the class’ properties:

Or get the constructor and learn about its parameters:

Conclusion

While you may not use reflection daily, there are times it can come in very handy – working with other people’s code, for example. I encourage you to checkout the links in the Further Reading section below to learn more.

Further Reading

Reflection (PHP Docs)
What is Reflection in PHP?
Introduction to PHP Reflection API