The Closure class

Introduction

Anonymous functions, implemented in PHP 5.3, yield objects of this type.
This fact used to be considered an implementation detail, but it can now
be relied upon. Starting with PHP 5.4, this class has methods that allow
further control of the anonymous function after it has been created.

Besides the methods listed here, this class also has an
__invoke method. This is for consistency with other
classes that implement calling
magic, as this method is not used for calling the function.

User Contributed Notes 5 notes

This caused me some confusion a while back when I was still learning what closures were and how to use them, but what is referred to as a closure in PHP isn't the same thing as what they call closures in other languages (E.G. JavaScript).

In JavaScript, a closure can be thought of as a scope, when you define a function, it silently inherits the scope it's defined in, which is called its closure, and it retains that no matter where it's used. It's possible for multiple functions to share the same closure, and they can have access to multiple closures as long as they are within their accessible scope.

In PHP, a closure is a callable class, to which you've bound your parameters manually.

ScopeA closure encapsulates its scope, meaning that it has no access to the scope in which it is defined or executed. It is, however, possible to inherit variables from the parent scope (where the closure is defined) into the closure with the use keyword:

The problem: a function that calls another function which is passed in the arguments of the initial function. The callable might re-use the arguments of the initial function. Whatever the callable is we want a simple function for use in our code (here is where closure comes).

Example: a generic Header class that sends files (cached, not cached, for download, inline etc.). Probably readfile() is all you need right?But what when a captcha library has a function output() that you want to be used in the place of readfile()?

No big deal you might say, pass a callable in the function's arguments, but let's unwind the possibilities of the callable argument:1. it's another function in this scope,2. it's a class method,3. it's a static method of a class.

Php uses different helpers to call this argument-function:1. call_user_func_array(),2, 3. call_user_func_array() or Reflection.