Topics

programming

php drupal scheme scheming macros design patterns da la

design

design css

random thoughts

scribbles

alter ego

other me 'em that link us my space me linked in

Collections

Programmable web
PHP design patterns

guild

Emulating closures in PHP

Submitted by vlado on Tue, 2006-01-24 09:03.articles | code | design patterns | lisp | php | programming | scheme | scribbles | shorts
In programming languages, a closure is an abstraction that combines a function and a special lexical environment bound to that function (scope). The variables in the lexical environment are designed to retain state information between function calls. Unlike garden-variety functions which retain no memory of what happened in previous calls, closures are capable of storing information across function calls.closulres in computer science (wikipedia)

PHP doesn't have closures as an element of the language. What can we do to emulate it?

We need to be able to encapsulate in one entity scope, state and execution. The most obvious candidate will be a PHP object.

With the introduction of the __get(), __set() and __call() magic functions for PHP classes, something the manual calls overloading, PHP opens the gate to transparently enhance a class to add variables and methods to an object's body. We can abuse the __get() to implemet nested scopes. The state is preserved as part of the object body. The default function (call()) is a protocol to add a uniformity of execution between different function objects.

class function_object { var $scope; function __get($name) { return $this->$scope->$name; } function __constructor($scope) { $this->scope=$scope; } function call() { //the function body - do some work } } If all $scope objects are function objects we get a closure emulation in PHP. This opens the doors to such fancy ideas as namespaces, modules et.al. This technique opens the possibilities for functional style programming techniques and idioms as delayed evaluation, continuation, ...

Update: I've added closures to my design patterns collection

vlado's blog | 4 comments

Reply

Please solve the math problem above and type in the result. e.g. for 1+1, type 2
The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <br /> <br> <div> <a> <em> <strong> <cite> <pre> <code> <ul> <ol> <li> <dl> <dt> <dd> <h3> <img> <blockquote> <q> <strike> <small> <h4> <h5> <h6>
  • Link to content with [[some text]], where "some text" is the title of existing content or the title of a new piece of content to create. You can also link text to a different title by using [[link to this title|show this text]]. Link to outside URLs with [[http://www.example.com|some text]], or even [[http://www.example.com]].
  • Lines and paragraphs break automatically.
More information about formatting options
Home ยป Emulating closures in PHP

dikini.net

spreading confusion by accident since 1970