Re: Closures and __FUNCTION__
| From: | Justin Martin | Date: | Mon, 13 Apr 2009 08:00:09 +0000 |
| Subject: | Re: Closures and __FUNCTION__ | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-43668@lists.php.net to get a copy of this message | ||
In addendum I'd like to correct the syntax that I had someone in IRC test.
Apparently it works as such:
$foo = NULL;
$foo = function($foo) use (&$foo) {
...
}
Still rather hackish, but better than globals I suppose?
Thanks,
Justin Martin
Justin Martin wrote:
> Hi Peter,
>
> If I recall correctly, you can use the 'use' keyword.
>
> $factorial = function($foo) use ($factorial) {
> $factorial($foo);
> }
>
> $factorial('Hello World!');
>
> I'm still having issues compiling 5.3 on my system, so I haven't tested
> this.
>
> Thanks,
> Justin Martin
>
> Peter Danenberg wrote:
>> The original anonymous functions patch[1] contained support for
>> __FUNCTION__ as a recursion mechanism in closures, such that I should
>> be able to do something like this:
>>
>> $factorial = function($n) {
>> if ($n == 1)
>> return 1;
>> else
>> return $n * call_user_func(__FUNCTION__, $n - 1);
>>
>> };
>>
>> print $factorial(3); // => 6
>>
>>
>> It fails with a warning, though:
>>
>> Warning: call_user_func() expects parameter 1 to be a valid
>> callback, function '{closure}' not found or invalid function name
>>
>> Is there another recursion mechanism for closures besides something
>> like the $GLOBALS['factorial'] hack?
>>
>> Footnotes:
>> [1]
>> http://marc.info/?l=php-internals&m=119995982228453&w=2
>>