Sevalla is the all-in-one PaaS for your web projects. Host and deploy your applications, databases, object storage, and static sites. Enjoy advanced deployment pipelines, a complete database studio, instant preview apps, and one-click templates. The pricing is simple: no hidden fees, no seat-based pricing, and you pay only for what you use. Get real human support from developers.

Get started now with a $50 credit at Sevalla.com.

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.

Stay up to date with all things Laravel, PHP, and JavaScript.

You can follow me on these platforms:

On all these platforms, regularly share programming tips, and what I myself have learned in ongoing projects.

Every month I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.