Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Closure examples.
// This works on Rhino.
var counter = (function () {
var i = 1;
return function () {
return i++;
};
})();
print(counter()); // 1
print(counter()); // 2
print(counter()); // 3
print(counter()); // 4
print(counter()); // 5
<?php
$i = 1;
$counter = function () use (&$i) {
return $i++;
};
echo $counter() . PHP_EOL; // 1
echo $counter() . PHP_EOL; // 2
echo $counter() . PHP_EOL; // 3
echo $counter() . PHP_EOL; // 4
echo $counter() . PHP_EOL; // 5
use strict;
use warnings;
use feature qw(say);
my $counter = sub {
my $i = 1;
return sub {
return $i++;
};
}->();
say $counter->(); # 1
say $counter->(); # 2
say $counter->(); # 3
say $counter->(); # 4
say $counter->(); # 5
# Not closure but generator.
def counter():
i = 0
while (True):
i += 1
yield i
counter = counter()
print counter.next() # 1
print counter.next() # 2
print counter.next() # 3
print counter.next() # 4
print counter.next() # 5
counter = lambda do
i = 0
lambda { i += 1 }
end.call
puts counter.call # 1
puts counter.call # 2
puts counter.call # 3
puts counter.call # 4
puts counter.call # 5
<?php
// This can't work because of parse error...
$counter = (function () {
$i = 0;
return function () use (&$i) {
return $i++;
};
})();
echo $counter() . PHP_EOL;
echo $counter() . PHP_EOL;
echo $counter() . PHP_EOL;
echo $counter() . PHP_EOL;
echo $counter() . PHP_EOL;
<?php
class Counter
{
protected $_i = 1;
public function __invoke()
{
return $this->_i++;
}
}
$counter = new Counter;
echo $counter() . PHP_EOL; // 1
echo $counter() . PHP_EOL; // 2
echo $counter() . PHP_EOL; // 3
echo $counter() . PHP_EOL; // 4
echo $counter() . PHP_EOL; // 5
<?php
class Counter
{
protected $_i = 1;
public function __toString()
{
return (string) $this->_i++;
}
}
$counter = new Counter;
echo $counter . PHP_EOL; // 1
echo $counter . PHP_EOL; // 2
echo $counter . PHP_EOL; // 3
echo $counter . PHP_EOL; // 4
echo $counter . PHP_EOL; // 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.