PHP comes built-in with something great known as the Reflection API. Sadly, not many people know about it. It’s just something that allows you to observe and/or modify programs in run-time. Essentially this is called reverse engineering.
Some use cases include:
- Checking whether certain methods are available
- Getting meta-information in comments
- Getting values of variables that are otherwise inaccessible
- Modifying states of methods and variables
- Invoking classes and methods with more control
To demo the PHP Reflection API, I will show you how to modify otherwise inaccessible variables. Let’s take a look at the following piece of code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <script type="text/javascript" language="php">// <![CDATA[ class one { protected $first = 1; public function getFirst() { return $this->first; } } class two extends one { protected $second = 2; public function getSecond() { return $this->second; } } class three extends two { protected $third = 3; public function getThird() { return $this->third; } } // More code // ]]></script> |
Now let’s add the following code, which creates an instance of the class “three.” It also prints out what you get when you call the method “getSecond.”
1 2 | $object = new three(); echo $object->getSecond(); |
The output, as we would expect, is “2″.
Notice how in the code there’s no direct way to modify the variable “$second.” With the Reflection API, this is possible.
Let’s add the following code:
1 2 3 4 5 6 | $rc = new ReflectionClass('three'); $rp = $rc->getProperty('second'); $rp->setAccessible(true); $rp->setValue($object, 4); echo $object->getSecond(); |
This part of the code will output “4″. Cool, isn’t it? For more information, consult the php manual.
Also, in case you were wondering, I used the script tag on purpose. Did you know it existed? Let me know below.