Skip to content

Instantly share code, notes, and snippets.

@tom--
Last active August 29, 2015 14:15
Show Gist options
  • Select an option

  • Save tom--/33e72187158d1932e95b to your computer and use it in GitHub Desktop.

Select an option

Save tom--/33e72187158d1932e95b to your computer and use it in GitHub Desktop.
Can PHP's so-called "closures" do any real closure work, like a revealing module? http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript
<?php
function constructTotalizer() {
$privateTotal = 0;
$privateAddTotal = function ($n) use (&$privateTotal) {
$privateTotal += $n;
};
$publicAddTotal = function ($n) use ($privateAddTotal) {
$privateAddTotal($n);
};
$publicIncremenet = function () use ($publicAddTotal) {
$publicAddTotal(1);
};
$publicGetTotal = function () use (&$privateTotal) {
return $privateTotal;
};
$that = new stdClass();
$that->add = $publicAddTotal;
$that->inc = $publicIncremenet;
$that->get = $publicGetTotal;
return $that;
};
$totalizer = constructTotalizer();
var_dump($totalizer);
$totalizer->add(2);
$totalizer->inc();
echo $totalizer->get() . "\n";
<?php
function constructTotalizer() {
$privateTotal = 0;
$privateAddTotal = function ($n) use (&$privateTotal) {
$privateTotal += $n;
};
$publicAddTotal = function ($n) use ($privateAddTotal) {
$privateAddTotal($n);
};
$publicIncremenet = function () use ($publicAddTotal) {
$publicAddTotal(1);
};
$publicGetTotal = function () use (&$privateTotal) {
return $privateTotal;
};
$that = [
'add' => $publicAddTotal,
'inc' => $publicIncremenet,
'get' => $publicGetTotal,
];
return $that;
};
$totalizer = constructTotalizer();
var_dump($totalizer);
$totalizer['add'](2);
$totalizer['inc']();
echo $totalizer['get']() . "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment