[doc-en] master: docs: improve closure variable inheritance example (#4826)
| From: | Josh via GitHub | Date: | Wed, 02 Sep 2026 12:47:25 +0000 |
| Subject: | [doc-en] master: docs: improve closure variable inheritance example (#4826) | ||
| Groups: | php.doc.cvs | ||
| Request: | Send a blank email to doc-cvs+get-23698@lists.php.net to get a copy of this message | ||
Author: Josh (joshtrichards)
Committer: GitHub (web-flow)
Pusher: lacatoire
Date: 2026-09-02T14:47:22+02:00
Commit: https://github.com/php/doc-en/commit/c19f29d4fcf92c1a2d2c46d68adab31e98fcbe78
Raw diff: https://github.com/php/doc-en/commit/c19f29d4fcf92c1a2d2c46d68adab31e98fcbe78.diff
docs: improve closure variable inheritance example (#4826)
Changed paths:
M language/functions.xml
Diff:
diff --git a/language/functions.xml b/language/functions.xml
index d97498f5a2d5..309e907c782c 100644
--- a/language/functions.xml
+++ b/language/functions.xml
@@ -1157,15 +1157,18 @@ $greet('PHP');
<programlisting role="php">
<![CDATA[
<?php
+// A variable defined in the parent scope
$message = 'hello';
-// No "use"
+// $message is not inherited and is undefined due to the
+// lack of a "use" clause
$example = function () {
var_dump($message);
};
$example();
-// Inherit $message
+// $message is inherited from the parent scope due to the
+// "use" clause
$example = function () use ($message) {
var_dump($message);
};
@@ -1176,17 +1179,16 @@ $example();
$message = 'world';
$example();
-// Reset message
+// Reset $message
$message = 'hello';
-// Inherit by-reference
+// Inheriting by reference: a change made in the parent scope
+// after the closure is defined is visible inside it
$example = function () use (&$message) {
var_dump($message);
};
$example();
-// The changed value in the parent scope
-// is reflected inside the function call
$message = 'world';
$example();
@@ -1196,24 +1198,30 @@ $example = function ($arg) use ($message) {
};
$example("hello");
-// Return type declaration comes after the use clause
-$example = function () use ($message): string {
- return "hello $message";
+// Closures can return values like any other function; the
+// return type declaration comes after the use clause
+$example = function () use ($message): array {
+ return ["hello", $message];
};
var_dump($example());
]]>
</programlisting>
- &example.outputs.similar;
+ &example.outputs;
<screen>
<![CDATA[
-Notice: Undefined variable: message in /example.php on line 6
+Warning: Undefined variable $message in script on line 8
NULL
string(5) "hello"
string(5) "hello"
string(5) "hello"
string(5) "world"
string(11) "hello world"
-string(11) "hello world"
+array(2) {
+ [0]=>
+ string(5) "hello"
+ [1]=>
+ string(5) "world"
+}
]]>
</screen>
</example>