Skip to content

docs: improve closure variable inheritance examples #4826

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 28 additions & 24 deletions language/functions.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1173,64 +1173,68 @@ $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);
var_dump($message); // undefined
};
$example();
$example(); // NULL

// Inherit $message
// $message is inherited from the parent scope due to the
// "use" clause
$example = function () use ($message) {
var_dump($message);
};
$example();
$example(); // "hello"

// Inherited variable's value is from when the function
// is defined, not when called
// was defined, not when called
$message = 'world';
$example();

// Reset message
$example(); // "hello"
// Reset $message
$message = 'hello';

// Inherit by-reference
// A changed value in the parent scope will be reflected
// when called if $message is passed by reference
$example = function () use (&$message) {
var_dump($message);
};
$example();

// The changed value in the parent scope
// is reflected inside the function call
$message = 'world';
$example();
$example(); // "world" instead of "hello"

// Closures can also accept regular arguments
// Closures can accept regular arguments
$example = function ($arg) use ($message) {
var_dump($arg . ' ' . $message);
};
$example("hello");
$example("hello"); // "hello world"

// Return type declaration comes after the use clause
$example = function () use ($message): string {
return "hello $message";
// Closures can return values like other function types
// and return type declaration comes after the "use"
$example = function () use ($message): array {
return ["hello", $message];
};
var_dump($example());
var_dump($example()); // array("hello", "world")
?>
]]>
</programlisting>
&example.outputs.similar;
<screen>
<![CDATA[
Notice: Undefined variable: message in /example.php on line 6
Warning: Undefined variable $message in /example.php 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>
Expand Down