简体   繁体   English

如何重写PHP函数?

[英]How to override a PHP function?

UberCart for Drupal has some difficulties with currencies. UberCart for Drupal在币种方面存在一些困难。 However, by overriding "uc_currency_format", you can at least do some background calculation to give you a good estimate of the converted value. 但是,通过覆盖“ uc_currency_format”,您至少可以进行一些背景计算,以便对转换后的值进行良好的估算。 However, as it's part of UberCart Core, you can't edit the file, So you risk losing your code after every update. 但是,由于它是UberCart Core的一部分,因此您无法编辑该文件,因此,每次更新后都有丢失代码的风险。 Also, this function does not have a hook! 另外,此功能没有挂钩!

That means the only that I can think of dealing with this, is having a module that overrides the function. 这意味着我唯一想到的就是拥有一个覆盖该功能的模块。 So my question is... 所以我的问题是

Is there a way to override an existing PHP function? 有没有办法覆盖现有的PHP函数? For example, I have: 例如,我有:

function uc_currency_format($value, $sign = TRUE, $thou = TRUE, $dec = NULL) 
{
    // dont do this
}

But when this gets called, I want it to instead execute this 但是当它被调用时,我希望它代替执行

function uc_currency_format_rewrite($value, $sign = TRUE, $thou = TRUE, $dec = NULL) 
{
    // do this
}

Is that possible? 那可能吗?

It seems to be one of those very rare times you need to hack the core code. 这似乎是您需要破解核心代码的极少数情况之一。 When it comes to this, I try to limit the impact at minimum like this: 当涉及到这一点时,我尝试将影响降到最低,例如:

  • Rename original function. 重命名原始功能。 In your case, you would go with something like 'uc_currency_format_ORIGINAL' 就您而言,您可以使用类似“ uc_currency_format_ORIGINAL”的名称
  • In your custom module, rename your 'uc_currency_format_rewrite' into 'uc_currency_format' 在您的自定义模块中,将“ uc_currency_format_rewrite”重命名为“ uc_currency_format”

This way, you will have your own code running. 这样,您将运行自己的代码。

At next update, you will see in your testing environment (always better to test, before applying updates to production sites) a duplicate function name fatal error. 在下一次更新时,您将在测试环境中看到(总是最好在将更新应用于生产站点之前进行测试)重复的功能名称致命错误。 If your hook has not been implemented yet, you will rename the original fuction, again. 如果尚未实现挂钩,则将再次重命名原始功能。

This method is not defined in the best practice, of course. 当然,最佳实践中并未定义此方法。 Use it at your own risk. 需要您自担风险使用它。

No it is not possible to override a function in PHP. 不可以,无法在PHP中覆盖函数。 Drupal 7 does not use Zend ( rename_function() , override_function() ) or OOP in modules. Drupal 7在模块中不使用Zend( rename_function()override_function() )或OOP。 So you could only ask the maintainer for a new hook. 因此,您只能要求维护者提供新的挂钩。 Maybe you could write a patch, which provides this hook and ask the maintainer for implementing it. 也许您可以编写一个补丁来提供此挂钩,并要求维护人员实施它。

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

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