This post is archived and probably outdated.

Class posing and overloading the "new" operator

2010-01-01 19:39:00

Two years ago at some conference I had a conversation with Sebastian about the need for a way to overload the new operator in PHP so, probably, bad designed code can be tested more easily by replacing specific classes with mocks. On the train ride home -- I like coding on a train without the disturbing Internet -- I came up with a proof-of-concept extension for PHP and sent it to Sebastian.

Then we more or less forgot about it or did other things until a few days ago where both, Sebastian and I, independently remembered it. Sebastian then pushed the code as part of a new test_helpers extension with some documentation to github and I fixed some bugs in it. The aim of the extension is to collect functionality which might be beneficial for phpUnit and other test scenarios but which should never reach a production environment.

Currently only the new overloading is part of this extension. A simple example might look like this:

<?php
class Foo {}
class Bar {}

function callback($className) {
    if ($className == 'Foo') {
        $className = 'Bar';
    }

    return $className;
}

var_dump(get_class(new Foo));

set_new_overload('callback');
var_dump(get_class(new Foo));
?>

Which will print

string(3) "Foo"
string(3) "Bar"

Today Sebastian was brave and released it as 1.0.0 on phpUnit's PEAR channel. Please refer to the README for further information.