Skip to content
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

describe behavior of static variables inside anonymous functions #4377

Merged
merged 2 commits into from
Jan 27, 2025
Merged
Changes from 1 commit
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
31 changes: 31 additions & 0 deletions language/variables.xml
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,37 @@ function foo(){
</example>
</para>

<simpara>
Static variables inside anonymous functions persist only within that
specific function instance. If the anonymous function is recreated on each
call, the static variable will be reinitialized.
</simpara>
<para>
<example>
<title>Static variables in anonymous functions</title>
<programlisting role="php">
<![CDATA[
<?php
function exampleFunction($input) {
$result = (static function () use ($input) {
static $counter = 0;
$counter++;
return "Input: $input, Counter: $counter\n";
});

return $result();
}

// Calls to exampleFunction will recreate the anonymous function, so the static
// variable does not retain its value.
echo exampleFunction('A'); // Outputs: Input: A, Counter: 1
echo exampleFunction('B'); // Outputs: Input: B, Counter: 1
?>
]]>
</programlisting>
</example>
</para>
Girgias marked this conversation as resolved.
Show resolved Hide resolved

<para>
As of PHP 8.1.0, when a method using static variables is inherited (but not overridden),
the inherited method will now share static variables with the parent method.
Expand Down
Loading