Monkey patching in PHP

Tuesday, June 22. 2010
Comments

I haven't really had the chance or time to play with PHP 5.3 until recently when Ubuntu 10.04 upgraded my local installations and kind of forced me to dive into it a little. And I'm also probably the last person on the planet to notice, but namespaces in PHP 5.3 allow you to monkey-patch core PHP code.

What's monkey patching?

So monkey patching is a technique to replace functions at runtime. One of the more common applications is stubbing (or mocking) code in unit tests. So for example mocking the response from a server allows you to run a unit test in absence of another external service. Thus making your test suite both more robust and possible bugs easier to squash.

Up until 5.3 monkey patching was not available in PHP — unless you used the runkit extension.

Other use cases are changing the behavior of code without directly forking it and maintaining a local copy, e.g. to add a feature or so or even to apply bug fixes without modifying the original code.

Example

Here's some example code.

<?php
namespace monkeypatch;

$str = 'your mom';

echo "This should eight, but it's not: " . strlen($str) . "\n"; // 6
echo "Now this should be really eight: " . \strlen($str) . "\n";

function strlen($str) {
    return 6;
}

The difference between strlen() and \strlen() is, that the first call uses the function we defined in the current namespace. Since using the namespace operator requires it to be the first thing in a file, all consecutive functions and classes are part of this namespace. If an equivalent is not available in the current namespace, it'll fall back to the parent namespace or root.

Other applications that come to mind would be fixing the parameter order in strstr() and in_array(), and similar! But of course I'm kidding and wouldn't suggest that really. :-)

Fin

That's all kids!