PHP Closures

Closures are anonymous functions and are like lambda functions, but smarter in the sense that they have the ability to interact with variables from the outside environment of where the closure is defined. They are functions created without a name, and they are generally passes and callback handlers to other functions.

Added in PHP 5.3, these functions are typically created on the fly, and as such didn’t have access to objects outside of what were being passes arguments to the function. PHP 5.4 adds the ability to access the this scope and therefore the scope of the parent PHP document class.

I’ll demonstrate with a simple example. I’ll create a file called closers.php and create a new class in it called Event. This class is going to have a private property called $name, I’ll just set it my name.

Next I will create a function, and this function is going to return an instance of a function.


class Event
private $name = "Michelle";

public function getFunction ()
return function () { return $this->name; };


$event = new Event();
$func = $event->getFunction();

echo "Hello, ", $func();


Now, with PHP 5.4, this function is going to actually be able to access the $this scope. You may wonder why would I would create a function that returns a function? I do this because the benefit of passing functions around like variables allows us to essentially
encapsulate logic that can be called at a later time in code execution.

A good reason to do this is when you want something to happen after another event occurs.

For example, if I call a web service and I want to call another function to process the results when they comeback, this is a good way to do it. You can create your own special events.

They take functions and arguments and use them to call them at appropriate times at runtime. So what I can do is in my function I simply return, and then now that I have access to the $this scope I can just output what’s in the name property.

So that’s my event class. Now to use it I can create a new instance.

$event = new Event();

I can then call on that function to set a variable equal to that function object, which I can call at a later time.

$func = $event->getFunction();

So because func is now that function, I can now output the result by calling it. So what I should see when I run this is Hello Michelle, and it does this by calling the function that I returned in my class.

So closures, or anonymous functions, were a new addition in PHP 5.3. However, there is internal disagreement among PHP developers as to what the PHP $this scope should refer to exactly. Because of that, it didn’t allow access to it.

Now in 5.4, the PHP $this scope has been allowed, and you can use it to reference instance functions and properties as in the example above.

Tags: , ,

Comments are closed.