News Feed
Jobs Feed
Sections




News Archive
Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Ryan Gantt's Blog:
Anonymous recursion in PHP
August 11, 2011 @ 10:55:35

In a recent post to his blog Ryan Gantt looks at an interesting way to get around a limitation in PHP dealing with anonymous recursion and closures that throws a Fatal error when called.

Turns out that variables called as functions must be an instance of Closure, an instance of a class which implements __invoke(), or a string representing a named function in the global namespace. In the anonymous function body above, $fibonacci is none of these. It is an undeclared, free variable in the closure created by the anonymous function. At the time when it's called, it hasn't been bound-hence the Notice that you would have gotten if error reporting were set at a high enough threshold - and therefore can't be called as anything, let alone as a function.

He tried using the "use" functionality PHP closures have to bring a variable/object/etc into the scope of the running function, but it still threw an error. As it turns out, the combination of "use"-ing the object and calling it by reference handles things correctly. He takes this method and applies it in two examples - one call in an array_map function and another in an array_reduce.

0 comments voice your opinion now!
anonymous recursion reference invoke closure


blog comments powered by Disqus

Similar Posts

Josh Adell's Blog: Command Invoker Pattern with the Open/Closed Principle

PHP Tip-a-Day: PHP Tutorial: Convoluted Code - Combining Ternary Operators and Anonymous Functions

Mayflower Blog: Zend Framework Application.ini Cheat Sheet

IBM developerWorks: What's new in PHP V5.3, Part 2: Closures and lambda functions

DevShed: Developing a Discussion Forum in PHP with Recursion (Part 3)


Community Events











Don't see your event here?
Let us know!


introduction symfony2 application project hhvm release language example install performance security hack package component podcast framework database unittest facebook composer

All content copyright, 2014 PHPDeveloper.org :: info@phpdeveloper.org - Powered by the Solar PHP Framework