If I have a function:
function this($a){
return $a;
}
If I wanted to redefine the function, would it be as simple as rewriting it?
function this($a, $b){ //New this function
return $a * $b;
}
We started with Q&A. Technical documentation is next, and we need your help.
Whether you're a beginner or an experienced developer, you can contribute.
|
Nope, that throws an error:
The runkit provides options, including |
||||
|
If you mean overloading in a Java sense, then the answer is no, this is not possible. Quoting the PHP manual on functions:
You could use the If by redefine you mean add to an existing userland function, refactor, substitute or rewrite, then yes: it is as simple as you've shown. Just add the additional code to the function, but make sure you set a default for backwards compatibility. Another option would be to use http://antecedent.github.io/patchwork
|
|||||||||||||||||
|
You can't redefine or 'undefine' a function in PHP (without resorting to third-party modules). However, you can define a function conditionally. So, if you know function A can be defined elsewhere, but not always, you can wrap it like this:
Then you only need to make sure the implementation you want is encountered first:
|
|||||
|
I've got a library of functions that sometimes I just don't want invoked while I'm testing (typically database updates). If I have, for example, a few different db update functions that are all over the code. instead of commenting out the code, I just create a special class (e.g. class foo {}). Define a global variable (e.g., $DEBUG) and a dummy function (e.g., function dummy {}). Inside foo define all the (public static) functions you need to mimic as $fn = isset($DEBUG) ? 'dummy' : 'real function'; return call_user_func_array($fn,func_get_args()); Plus you have the advantages of now doing other things, like logging the calls and parameters. Then simply replace all your calls to real_function(...) with foo::real_function(...). Usually just a simple search/replace (or leave it there; depending on what's going on in the function and how often it's getting called the overhead may be irrelevant). |
|||
|
You can't have both functions declared at the same time, that will give an error. |
|||||
|
You can't redeclare it. If your question is just about overloading that example, how about:
|
|||
|
Setting an appropriate default to any new arguments that you add might help for backwards compatibility, i.e.:
I also recommend, for clarity, generally avoiding using |
|||
|
I have good news and bad news. The good news
The nadnews
And the second bad news: You havbe to sacrifice code readability. Example:
Oh, and one more thing, using
|
||||
|