File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff 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.
You can’t perform that action at this time.
0 commit comments