1
2<?php
3$message = 'hello';
4
5// No "use"
6$example = function () {
7 var_dump($message);
8};
9$example();
10
11// Inherit $message
12$example = function () use ($message) {
13 var_dump($message);
14};
15$example();
16
17// Inherited variable's value is from when the function
18// is defined, not when called
19$message = 'world';
20$example();
21
22// Reset message
23$message = 'hello';
24
25// Inherit by-reference
26$example = function () use (&$message) {
27 var_dump($message);
28};
29$example();
30
31// The changed value in the parent scope
32// is reflected inside the function call
33$message = 'world';
34$example();
35
36// Closures can also accept regular arguments
37$example = function ($arg) use ($message) {
38 var_dump($arg . ' ' . $message);
39};
40$example("hello");
41?>
42
43