Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
73

■ ■ ■


CHAPTER 7


Reflection API


Reflection is one of the most powerful and perhaps one of the most underused features of the
PHP language. If you’re tasked with building complex, extensible applications, it’s well worth
your time to understand this powerful feature. Reflection can facilitate otherwise tedious and
complicated tasks, such as autoloading plug-ins, automating documentation, and even extending
the PHP language itself.
How can one feature offer such a wide array of capabilities? PHP’s reflection API consists
of a series of classes that allow you to access program metadata and interact with associated
code comments. This gives you the ability to determine, for example, what methods a class
implements. With this capability, you can create applications that load plug-ins without creating a
rigid plug-in interface. This means that you can implement as few or as many methods of a
supported API as you wish.
Reflection offers much more than the ability to review class metadata. It can also be used
to create instances of classes, invoke functions, and pass arguments pragmatically. The reflec-
tion API even allows you to invoke static methods of classes dynamically. As mentioned in the
previous chapter, reflection also can be used to create autodocumenting systems.
In this chapter, you will learn how, using reflection, you can create efficient plug-in-based
systems. You will build a reflection-based documentation parser using the doccomments
discussed in Chapter 6. Then you will learn how to add capabilities to the reflection API by
extending the built-in classes. You will build a fully functional extended API that will parse your
docblock comments into additional program metadata. Finally, you will learn how these tech-
niques can be used to simulate attributes in the PHP language and allow for some very advanced
OOP interaction.

Introducing the Reflection API


The reflection API is one of several built-in OOP extensions to PHP. It is a series of classes,
exceptions, and interfaces that come together to allow you to analyze other classes, interfaces,
methods, properties, functions, and extensions. This extension is appropriately named reflection
and can be found in the PHP source under /ext/reflection, along with many useful examples
and unit tests.

McArthur_819-9C07.fm Page 73 Friday, February 22, 2008 8:59 AM

Free download pdf