Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you make a PHP function recursive without repeating its name?

Tags:

php

recursion

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.

like image 550
alex Avatar asked Apr 27 '10 05:04

alex


People also ask

What does recursive mean in PHP?

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.

Does PHP allow recursion?

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.

Can a recursive method call itself more than once?

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.


2 Answers

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.

like image 155
Felix Kling Avatar answered Sep 19 '22 20:09

Felix Kling


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.

like image 41
Alix Axel Avatar answered Sep 19 '22 20:09

Alix Axel