Jump to content

Recursive anonymous function help

- - - - -

  • Please log in to reply
2 replies to this topic

#1
Fighter

Fighter

    Newbie

  • Members
  • PipPip
  • 28 posts
I was attempting to build an anonymous function with function_create() but it was restrictive, I had read up about lambda functions and came up with the following but to no avail:
$factorial = function($n) {

    if($n <= 0) return 1;

    return $factorial($n - 1) * $n;

};

I believe you would call that a lambda function with enclosure. How would I do this?

#2
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,124 posts
  • Location:Vancouver, Eh! Cleverness: 200
Hi,

You will need to pass a reference of the lambda function you will be creating,
<?php
$factorial = function($n) use (&$factorial) {
    if($n <= 0) 
        return 1;
    return $factorial($n - 1) * $n;
};

print $factorial(5);

this "use" in PHP 5.3 will reference in parent scope and is considered late binding.

You can find a reference to its uses in PHP manual: PHP: rfc:closures [PHP Wiki]

Hope this helps!
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#3
Fighter

Fighter

    Newbie

  • Members
  • PipPip
  • 28 posts
This is exactly what I wanted, thank you so much for the example Null. I quite like this language




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users