Perl example:
1 2 3 4 5 6 7 8 9 10 11 12 13 | #!/usr/bin/perl sub test_it { my ( $count ) = @_ ; return sub { ++ $count ; }; } my $test1 = test_it(10); my $test2 = test_it(50); print $test1 ->(), "\n" ; # 11 print $test2 ->(), "\n" ; # 51 print $test1 ->(), "\n" ; # 12 print $test2 ->(), "\n" ; # 52 |
PHP distinguishes between read-only closures or read-write closures:
#!/usr/bin/php <?php function test_it_ro($count) { return function() use($count) { return ++$count; }; } function test_it_rw($count) { return function() use(&$count) { return ++$count; }; } $test1 = test_it_ro(10); $test2 = test_it_ro(50); print $test1()."\n"; // 11 print $test2()."\n"; // 51 print $test1()."\n"; // 11 print $test2()."\n"; // 51 $test1 = test_it_rw(10); $test2 = test_it_rw(50); print $test1()."\n"; // 11 print $test2()."\n"; // 51 print $test1()."\n"; // 12 print $test2()."\n"; // 52 ?>