File tree 1 file changed +29
-0
lines changed
1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change @@ -527,6 +527,35 @@ function foo(){
527
527
</example >
528
528
</para >
529
529
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
+
530
559
<para >
531
560
As of PHP 8.1.0, when a method using static variables is inherited (but not overridden),
532
561
the inherited method will now share static variables with the parent method.
You can’t perform that action at this time.
0 commit comments