简体   繁体   English

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

[英]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. 我正在寻找一种方法来重新声明,覆盖或重命名PHP4中的函数,以便在调用另一个函数的类上执行单元测试。 I want this function to be a test function instead. 我希望这个函数成为测试函数。

I have several constraints: 我有几个限制:

  • It has to work for PHP4. 它必须适用于PHP4。
  • It has to work right out-of-the-box WITHOUT installing something else. 它必须开箱即用而不安装其他东西。 (No adp or whatever). (没有adp或其他)。

Technically, it is possible using the override_function() or rename_function() functions. 从技术上讲,可以使用override_function()rename_function()函数。

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. 例如,我不建议将$calc_helper变量保留为public - 我会实现某种方法来让你改变它。

for overwriting the function you can check if function exits using function_exists but you can redeclare the function 要覆盖该函数,您可以使用function_exists检查函数是否退出但是您可以重新声明该函数

if (!function_exists('function_name')) {
    // ... proceed to declare your function
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM