Created
October 24, 2014 10:36
-
-
Save zburgermeiszter/d3dbdc6c022fc90f0e86 to your computer and use it in GitHub Desktop.
Function lazy-loading
This file contains 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 lazy-loading with anonymous functions (closures) | |
Benefit: we can evaluate each test on demand instead of evaluating all, and find the failed. | |
*/ | |
// Test case selector | |
$testCase = "closure"; | |
//$testCase = "direct-call"; | |
// Test functions | |
function trueTest() { | |
return true; | |
} | |
function falseTest() { | |
return false; | |
} | |
function veryHeavyTest() { | |
for($i=0;$i<100000000;$i++) { | |
$a = 0; | |
} | |
die("It takes too long"); | |
} | |
if($testCase == "closure") { | |
$arrayWithAnonFunc = array( | |
"x" => function() { | |
return trueTest(); | |
}, | |
"y" => function() { | |
return falseTest(); | |
}, | |
"z" => function() { | |
return veryHeavyTest(); | |
} | |
); | |
var_dump($arrayWithAnonFunc); | |
// Find the first failed test | |
foreach($arrayWithAnonFunc as $key => $anonymousFunction) { | |
if($anonymousFunction() == false) die("Test Failed @ " . $key); | |
} | |
} | |
if($testCase == "direct-call") { | |
$arrayWithoutAnonFunc = array( | |
"x" => trueTest(), | |
"y" => falseTest(), | |
"z" => veryHeavyTest() | |
); | |
var_dump($arrayWithoutAnonFunc); | |
// Find the first failed test | |
foreach($arrayWithoutAnonFunc as $key => $function) { | |
if($function() == false) die("Test Failed @ " . $key); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment