Emulating closures in PHP

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) {
  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


i like =)

another implementation

[[http://steike.com/PhpClosures|php closures@steike.com]]

cloning or referencing

Depending on application different scope types can be implemented - dynamic or lexical scopes. My initial hunch is that it can be done using different assignment strategies - deep copy or refence.

Somebody posted a comment,

Somebody posted a comment, which I accidentally deleted, sorry, saying that they stumble upon another closure implementation

Powered by Drupal, an open source content management system