Anonymous functionsAnonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses. Anonymous functions are implemented using the Closure class. Example #1 Anonymous function example
<?php Closures can also be used as the values of variables; PHP automatically converts such expressions into instances of the Closure internal class. Assigning a closure to a variable uses the same syntax as any other assignment, including the trailing semicolon: Example #2 Anonymous function variable assignment example
<?php Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct. From PHP 7.1, these variables must not include superglobals, $this, or variables with the same name as a parameter. Example #3 Inheriting variables from the parent scope
<?php The above example will output something similar to: Notice: Undefined variable: message in /example.php on line 6 NULL string(5) "hello" string(5) "hello" string(5) "hello" string(5) "world" string(11) "hello world" Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from). See the following example: Example #4 Closures and scoping
<?php Example #5 Automatic binding of $this
<?php The above example will output: object(Test)#1 (0) { } Output of the above example in PHP 5.3: Notice: Undefined variable: this in script.php on line 8 NULL As of PHP 5.4.0, when declared in the context of a class, the current class is automatically bound to it, making $this available inside of the function's scope. If this automatic binding of the current class is not wanted, then static anonymous functions may be used instead. Static anonymous functionsAs of PHP 5.4, anonymous functions may be declared statically. This prevents them from having the current class automatically bound to them. Objects may also not be bound to them at runtime.
Example #6 Attempting to use $this inside a static anonymous function
<?php The above example will output: Notice: Undefined variable: this in %s on line %d NULL
Example #7 Attempting to bind an object to a static anonymous function
<?php The above example will output: Warning: Cannot bind an instance to a static closure in %s on line %d Changelog
Notes
|