tags:

views:

207

answers:

4

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 default php version. Is this possible in php?

The reason I want to do this is because I have thousands of lines of code which call mail() and I don't want to rewrite all of them.

Also for future reference, in computer programming, what is it called when you do something like this?

Thanks

+2  A: 

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.

Pekka
-1 The reference is wrong. It needs to be edited.
Ewan Todd
@ewan Halfway down the page, "PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions."
Tim Lytle
Tim. Right, that's the bit that needs to be edited. See Milan's answer and your own.
Ewan Todd
Edited the answer to reflect that.
Pekka
+5  A: 

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.

Tim Lytle
lesson learned. Do you know if there is a reason php does not overload? It seems like a useful tool.
chris
+1  A: 

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.

Raveren
+5  A: 

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

Milan Babuškov
This seems simpler to do than runkit.
Ewan Todd
thanks. you know the php language very well.
chris