monkey patching in php

w00 picture w00 · Apr 8, 2012 · Viewed 9.4k times · Source

I'm trying to figure out how monkey patching works and how I can make it work on my own objects/methods.

I've been looking at this lib, it does exactly what I want to do myself: https://github.com/antecedent/patchwork

With it you can redefine a method from an object. It uses the 'monkey patch' technique for that. But I couldn't really figure out what exactly is going on by looking at the source.

So suppose I have the following object:

//file: MyClass.php
namespace MyClass;

class MyClass {

    public function say()
    {
        echo 'Hi';
    }
}

I'd like to do something like this:

Monkeypatch\replace('MyClass', 'say', function() {
    echo 'Hello';
});

$obj = new MyClass();
$obj->say();  // Prints: 'Hello'

But i'm not sure how to code the actual patching part. I know namespaces in this context are important. But how does that exactly let me patch a certain method? And do I need to use eval() somewhere (if so, how)?

I couldn't really find any good examples about this matter, except: http://till.klampaeckel.de/blog/archives/105-Monkey-patching-in-PHP.html

But I really don't see how I can apply that to my own objects/methods. I'm hoping for a good explanation or example.

Answer

tabdulla picture tabdulla · Apr 8, 2012

You can do runtime class modification using runkit. More specifically, you can use runkit_method_redefine.