Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

Monkey patch PHP classes with the BetterReflection Library

Link –

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.

Share Post LinkedIn

I write about Laravel, PHP, AI and building better software.

Every two weeks, I share practical tips, tutorials, and behind-the-scenes insights from maintaining 300+ open source packages. Join thousands of developers who read along.

No spam. Unsubscribe anytime. You can also follow me on X.

Found something interesting to share?

The community section is a place where developers share links to articles, tutorials and videos. Submit a link and help fellow developers discover great content. As a thank you, you'll receive a coupon for a discount on Spatie products.