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;
}
You can't redefine or 'undefine' a function in PHP (without resorting to third-party modules). However, you can define a function conditionally. With the further caveat that calls come after definitions. (Recent PHP doesn't care about call/define order for unconditionally defined functions.)
The fn keyword is used to create arrow functions. Arrow functions are only available in PHP versions 7.4 and up. Arrow functions have access to all variables from the scope in which they were created.
Nope, that throws an error:
Fatal error: Cannot redeclare foo()
The runkit provides options, including runkit_function_rename()
and runkit_function_redefine()
.
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.
You could use the runkit
extension but usage of runkit in production scenarios is generally considered doubtful practice. If you want to exchange algorithms at runtime, have a look at the Strategy pattern or Anonymous functions instead.
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
Patchwork is a PHP library that makes it possible to redefine user-defined functions and methods at runtime, loosely replicating the functionality
runkit_function_redefine
in pure PHP 5.3 code, which, among other things, enables you to replace static and private methods with test doubles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With