Last active
August 29, 2015 14:15
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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