Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer. You can expect quick tips, links to interesting tutorials, opinions and packages. Want to learn the cool stuff? Then sign up now!

Monkey patch PHP classes with the BetterReflection Library

At the PHP Benelux conference James Titcumb did a presentation on the BetterReflection library he’s working on. You can view the slides of his presentation on SlideShare.

The BetterReflection library has a few advantages over PHP’s native reflection capabilities (copied from the docs):

  • you can reflect on classes that are not already loaded, without loading them
  • ability to reflect on classes directly from a string of PHP code
  • better Reflection analyses the DocBlocks (using phpdocumentor/type-resolver)
  • reflecting directly on closures

When this pull request will get merged the library even makes it possible to monkey patch classes. Let’s take a look how you would do that.

Consider this class:

class MonkeyPatchMe
    function getMessage() : string
        return 'hello everybody';

The body of the getMessage-function can be replaced using this code:

$classInfo = ReflectionClass::createFromName('MonkeyPatchMe');

$methodInfo = $classInfo->getMethod('getMessage');

$methodInfo->setBody(function() {
   return 'bye everybody';

$monkeyPatchedClass = new MonkeyPatchMe();
$monkeyPatchedClass->getMessage() // returns 'bye everybody'

Behind the scenes this voodoo works by copying the original class to another file, doing a replacement of the function body there and loading up that class.

I’ll be keeping my eye on how the BetterReflection library evolves. You can read all about it’s current functionality in the docs on GitHub.

Freek Van der Herten is a partner and developer at Spatie, an Antwerp based company that specializes in creating web apps with Laravel. After hours he writes about modern PHP and Laravel on this blog. When not coding he’s probably rehearsing with his kraut rock band. He loves waffles and butterflies.
  • dakira

    Are there RFCs for getting this into PHPs native reflection API?

  • Asgrim

    FYI the API for instantiating a monkey patched class will likely be a little different, we’re still work with on that. Thanks for the post though, nice write up! 🙂

  • Oli

    An ability to add a method to a class would be exceptional.