tags:

views:

386

answers:

5

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;
}
A: 

You can't have both functions declared at the same time, that will give an error.

googletorp
+4  A: 

Nope, that throws an error:

Fatal error: Cannot redeclare foo()

The runkit provides options, including runkit_function_rename() and runkit_function_redefine().

Adam Backstrom
+2  A: 

If you mean overloading in a Java sense, then the answer is no, this is not possible.

Quoting the PHP manual on functions:

PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.

If by redefine you mean refactor, substitute or overwrite, then yes: it is as simple as you've shown.

Clearification: by which I mean, modifying the existing function body, not adding a new function with the same name and different body, which would be overloading. Sometimes it helps to understand an answer before downvoting it.

Gordon
A: 

You can't redeclare it. If your question is just about overloading that example, how about:

function this($a, $b=1)
{
    return $a * $b;
}
Tom
A: 

Setting an appropriate default to any new arguments that you add might help for backwards compatibility, i.e.:

function this($a, $b=1){  //New this function with a sane default.
    return $a * $b;
}

I also recommend, for clarity, generally avoiding using this for function/variable names.

Tchalvak