Skip to content

Instantly share code, notes, and snippets.

@zburgermeiszter
Created October 24, 2014 10:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zburgermeiszter/d3dbdc6c022fc90f0e86 to your computer and use it in GitHub Desktop.
Save zburgermeiszter/d3dbdc6c022fc90f0e86 to your computer and use it in GitHub Desktop.
Function lazy-loading
<?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