Is it possible to replace a function in php (such as mail) and make it do something else?

前端 未结 4 973
失恋的感觉
失恋的感觉 2020-11-28 11:45

I want to rewrite a function in PHP (let\'s say the mail() function), and want to make it so when I call mail() from now on, it will load my version of mail() and not the de

相关标签:
4条回答
  • 2020-11-28 12:34

    What you're referring to is generally called method overloading.

    While not generally supported by PHP, you actually may be able to redefine internal functions (as well as user functions) using runkit_function_remove() or runkit_function_redefine(). Of course to use that, you'll need to have pretty much full control over the PHP installation - since it's not bundled with PHP you'll need to install the runkit extension.

    Again, in a normal situation internal functions as well as user functions cannot be redefined (or overloaded) in PHP. This situation illustrates the benefit of wrapping some internal functions with a user function.

    0 讨论(0)
  • 2020-11-28 12:34

    It's called function overloading and is not possible in native PHP but possible using the extensions outlined in the other answers. The PHP documentation claims it is not possible at all: source which is incorrect.

    0 讨论(0)
  • 2020-11-28 12:36

    There is an extension that allows you to override functions. It is meant to be used for debugging, but I guess you can use it for your needs. Take a look:

    http://www.php.net/manual/en/function.override-function.php

    If you wish to call the original function within your version, make sure you read this comment: http://no.php.net/manual/en/function.override-function.php#50821

    0 讨论(0)
  • 2020-11-28 12:42

    You can use regexps to replace the function name in your files. What app you use is up to you, but I'd recommend the ovely-pricey Powergrep (unless you won't need it again).

    replace

       (\s+)mail([\s(]+)
    

    to

       $1new_function_name$2
    

    and

       ^mail([\s(]+)
    

    to

       new_function_name$1
    

    Sorry for my regexp-fu, I don't know how to search for either spaces OR begining of line in one expression.

    0 讨论(0)
提交回复
热议问题