Alex
Alex

Reputation: 44325

How can I redeclare, overwrite or rename a function in 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:

Upvotes: 0

Views: 99

Answers (2)

jcsanyi
jcsanyi

Reputation: 8174

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.

Upvotes: 2

Rohitashv Singhal
Rohitashv Singhal

Reputation: 4557

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
}

Upvotes: 0

Related Questions