0

I am looking for a way to redeclare, overwrite or rename a function in PHP4, in order to perform a unittest on a class that makes a call to another function. I want this function to be a test function instead.

I have several constraints:

  • It has to work for PHP4.
  • It has to work right out-of-the-box WITHOUT installing something else. (No adp or whatever).
Alex
  • 41,580
  • 88
  • 260
  • 469

2 Answers2

2

Technically, it is possible using the override_function() or rename_function() functions.

That's not a very clean way to handle it though, and instead I'd recommend that you update your class to allow you to redirect the call somewhere else.

For example, you can change this:

class MyClass {
    public function doSomething() {
        ...
        do_complex_calc();
        ...
    }
}

To something like this:

class MyClass {
    public $calc_helper = 'do_complex_calc';
    public function doSomething() {
        ...
        $helper = $this->calc_helper;
        $helper();
        ...
    }
}

$x = new MyClass();
$x->calc_helper = 'another_func_for_testing';
$x->doSomething();

That can be cleaned up even more, but it shows the general idea. For example, I wouldn't recommend leaving the $calc_helper variable as public - I'd implement some sort of a method to let you change it instead.

jcsanyi
  • 8,133
  • 2
  • 29
  • 52
  • Yes exactly, I got the same idea. This might even work for my task. Thanks – Alex Jun 27 '13 at 07:09
  • @Alex I just updated my answer to reflect the fact that it **is** possible, although I'd still recommend the way I originally described. – jcsanyi Jun 27 '13 at 07:15
0

for overwriting the function you can check if function exits using function_exists but you can redeclare the function

if (!function_exists('function_name')) {
    // ... proceed to declare your function
}
Rohitashv Singhal
  • 4,517
  • 13
  • 57
  • 105