PHP, possible to call the function from within the same function without specifying function name?

Go To StackoverFlow.com

3

Is it possible to call function within the same function without specifying the function name - e.g by using some sort of magic keyword?

2012-04-04 20:23
by vamur
sounds like a bad idea, what ever your asking - NoName 2012-04-04 20:24
@Dagon it sounds good for a recursion of generated functions - binarious 2012-04-04 20:28
@binarious If you're generating the functions, you should know their names. I've implemented half a dozen (related, code-sharing) code generators full of mutually-recursive functions in the last months, and in each code generator, I use a mapping with the name of every function to great effect - NoName 2012-04-04 20:29
@delnan No if they're anonymous functions - binarious 2012-04-04 20:33
@binarious If you need recursion, you obviously shouldn't generate anonymous functions ;) Besides, I can think of large ranges of code generation tasks that become unnecessarily hard or entirely impractical if one is bent on anonymous functions. For instance, anything that needs to call a function from multiple places :) Moreover, it's really easy and gives you a shot at useful tracebacks and more readable output - implement a trivial symbol table along with identifier generation. That's like 20 lines of trivial code w/o blanks, and I made the function names relate to the input - NoName 2012-04-04 20:37
This is not the right place for this debate ;). And I belive that there are usecases for it - binarious 2012-04-04 20:40


5

Yes. The constant __FUNCTION__ gives you a string representation of the current function. (src)

function testMe() {
  print __FUNCTION__;
}

testMe(); // outputs "testMe"

You can then of course use this to call itself:

$func = __FUNCTION__;
$func();
2012-04-04 20:24
by Owen
Also, __METHOD__ if you're in an OO context - Alex Howansky 2012-04-04 20:27
Nice! Is this callable? ie $foo = FUNCTION($arg);, will be trying when I get home. I agree this can be abused, yet I can also imagine using this for generic recursive functions. I imagine it could apply to some algorithms - stefgosselin 2012-04-04 20:28
won't be callable directly, you have to stuff __FUNCTION__ into a var first. but could probably be useful if you want a recursive anonymous function ^ - Samuel Herzog 2012-04-04 20:30
@SamuelHerzog you could call it with call_user_func(__FUNCTION__), too - binarious 2012-04-04 20:34
Thank you, this works perfectly - vamur 2012-04-05 02:06


0

function someFunction($i)
{
     $method = __FUNCTION__;
     if ( $i > 0 )
     {
         return $method($i-1);
     }
     return $i;
}

simple example of recursion without knowing the functions name, will call itself for $i-times if $i is positiv.

2012-04-04 20:28
by Samuel Herzog
Ads