It's always bugged me a recursive function needs to name itself, when a instantiated class can use $this
and a static method can use self
etc.
Is there a similar way to do this in a recursive function without naming it again (just to cut down on maintenance)?
Obviously I could use call_user_func
or the __FUNCTION__
constant but I would prefer something less ugly.
Published November 13, 2021. Recursion is a programming solution in which a function calls itself. It is used to solve a variety of problems, all of which have in common a structure that contains repetition.
PHP supports recursion, or in simple words, we can call a PHP function within another function without any argument, just like in C++. 200 is considered to be the maximum recursion level to avoid any crash of code. Example 1: Code for displaying n numbers using recursive function in PHP.
A recursive implementation may have more than one base case, or more than one recursive step. For example, the Fibonacci function has two base cases, n=0 and n=1.
You can make use of variable functions and declare a variable with the function name at the beginning of you function (or wherever). No need for call_user_func
:
function test($i) {
$__name = __FUNCTION__;
if($i > 5) {
echo $i. "\n";
$__name($i-1);
}
}
Don't forget that using the real function name is probably more readable for other people :)
(at least provide a comment why you do this)
Update:
As @Alix mentions in his comment, it might be useful to declare $__name
as static
. This way, the value is not assigned over and over again to the variable.
I don't know why this is ugly:
return call_user_func_array(__FUNCTION__, func_get_args());
Versus:
return call_user_func_array('someFunction', func_get_args());
You would still need to use call_user_func_array()
if you're looking to cut down on maintenance (if your functions have [a lot / a different number] of arguments).
Other than that I don't see another way. Also a static method cannot reference itself using self::
, only to its class. You would also need to use the magic __METHOD__
constant to do that.
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