@@ -1157,15 +1157,18 @@ $greet('PHP');
11571157 <programlisting role =" php" >
11581158<![CDATA[
11591159<?php
1160+ // A variable defined in the parent scope
11601161$message = 'hello';
11611162
1162- // No "use"
1163+ // $message is not inherited and is undefined due to the
1164+ // lack of a "use" clause
11631165$example = function () {
11641166 var_dump($message);
11651167};
11661168$example();
11671169
1168- // Inherit $message
1170+ // $message is inherited from the parent scope due to the
1171+ // "use" clause
11691172$example = function () use ($message) {
11701173 var_dump($message);
11711174};
@@ -1176,17 +1179,16 @@ $example();
11761179$message = 'world';
11771180$example();
11781181
1179- // Reset message
1182+ // Reset $ message
11801183$message = 'hello';
11811184
1182- // Inherit by-reference
1185+ // Inheriting by reference: a change made in the parent scope
1186+ // after the closure is defined is visible inside it
11831187$example = function () use (&$message) {
11841188 var_dump($message);
11851189};
11861190$example();
11871191
1188- // The changed value in the parent scope
1189- // is reflected inside the function call
11901192$message = 'world';
11911193$example();
11921194
@@ -1196,24 +1198,30 @@ $example = function ($arg) use ($message) {
11961198};
11971199$example("hello");
11981200
1199- // Return type declaration comes after the use clause
1200- $example = function () use ($message): string {
1201- return "hello $message";
1201+ // Closures can return values like any other function; the
1202+ // return type declaration comes after the use clause
1203+ $example = function () use ($message): array {
1204+ return ["hello", $message];
12021205};
12031206var_dump($example());
12041207]]>
12051208 </programlisting >
1206- &example.outputs.similar ;
1209+ &example.outputs;
12071210 <screen >
12081211<![CDATA[
1209- Notice : Undefined variable: message in /example.php on line 6
1212+ Warning : Undefined variable $ message in script on line 8
12101213NULL
12111214string(5) "hello"
12121215string(5) "hello"
12131216string(5) "hello"
12141217string(5) "world"
12151218string(11) "hello world"
1216- string(11) "hello world"
1219+ array(2) {
1220+ [0]=>
1221+ string(5) "hello"
1222+ [1]=>
1223+ string(5) "world"
1224+ }
12171225]]>
12181226 </screen >
12191227 </example >
0 commit comments