Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redefining PHP function?

Tags:

function

php

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;
}
like image 976
Michael Avatar asked Apr 14 '10 20:04

Michael


People also ask

How to redefine a function in PHP?

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.)

What is FN in PHP?

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.


2 Answers

Nope, that throws an error:

Fatal error: Cannot redeclare foo()

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

like image 119
Annika Backstrom Avatar answered Oct 19 '22 06:10

Annika Backstrom


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.

like image 22
Gordon Avatar answered Oct 19 '22 06:10

Gordon