Skip to content

Commit

Permalink
Describe behavior of static variables inside anonymous functions (#4377)
Browse files Browse the repository at this point in the history
  • Loading branch information
pereorga authored Jan 27, 2025
1 parent 06e4d8f commit 7d80472
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions language/variables.xml
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,35 @@ 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>
<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>
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

0 comments on commit 7d80472

Please sign in to comment.