Skip to content

Commit 7d80472

Browse files
authored
Describe behavior of static variables inside anonymous functions (#4377)
1 parent 06e4d8f commit 7d80472

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

language/variables.xml

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,35 @@ function foo(){
527527
</example>
528528
</para>
529529

530+
<simpara>
531+
Static variables inside anonymous functions persist only within that
532+
specific function instance. If the anonymous function is recreated on each
533+
call, the static variable will be reinitialized.
534+
</simpara>
535+
<example>
536+
<title>Static variables in anonymous functions</title>
537+
<programlisting role="php">
538+
<![CDATA[
539+
<?php
540+
function exampleFunction($input) {
541+
$result = (static function () use ($input) {
542+
static $counter = 0;
543+
$counter++;
544+
return "Input: $input, Counter: $counter\n";
545+
});
546+
547+
return $result();
548+
}
549+
550+
// Calls to exampleFunction will recreate the anonymous function, so the static
551+
// variable does not retain its value.
552+
echo exampleFunction('A'); // Outputs: Input: A, Counter: 1
553+
echo exampleFunction('B'); // Outputs: Input: B, Counter: 1
554+
?>
555+
]]>
556+
</programlisting>
557+
</example>
558+
530559
<para>
531560
As of PHP 8.1.0, when a method using static variables is inherited (but not overridden),
532561
the inherited method will now share static variables with the parent method.

0 commit comments

Comments
 (0)