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

Issue

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.

Solution

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.

Answered By – Felix Kling

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published