如何在PHP4中重新声明,覆盖或重命名函数?

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).

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
}

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.