tags:

views:

161

answers:

2

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.

Update

Thanks for your answers. I might stick to including the function name for simple functions, and make take the other approaches for anything more complicated.

+4  A: 

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.

Alix Axel
Regarding `self::`, that's what I meant. You can access other methods in that same class with it. I just thought it looks ugly compared to something simple like `self`.
alex
Thanks for your answer Alix +1
alex
@alex: Thanks, no problem! =)
Alix Axel
+5  A: 

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.

Felix Kling
Forgot about those. That does look a bit nicer than `call_user_func_array()`. Thanks +1
alex
+1, that's cheating! =P
Alix Axel
I agree with your last point. However I feel you *should* be able to rename a function without breaking recursive calls. Although I do realise changing function names breaks any call to it elsewhere. I guess this is why you should pick really good function names from the beginning!
alex
I'm going to accept this answer as it looks cleaner to me. Thanks for taking the time.
alex
@alex: It makes sense to make `$__name` static: `static $self = __FUNCTION__;`.
Alix Axel
Is `__FUNCTION__` set at interpretation time or run time? Hmm.. I'm sensing a new question coming on here.
alex