Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jensstalder/4d86f8de99c4823a316efb9ddab6ef35 to your computer and use it in GitHub Desktop.
Save jensstalder/4d86f8de99c4823a316efb9ddab6ef35 to your computer and use it in GitHub Desktop.
unction that demonstrates how to use closures to generate blocks of independent logic without extracting things into separate methods/functions. This avoids fragmentation of the code and allows to keep the logic in one place if the pieces are not reused/reusable, but still allows for save scoping. As explained by Brian Will: https://youtu.be/QM1…
<?php
/**
* Function that demonstrates how to use closures to generate blocks of independent logic without extracting things into separate methods/functions.
*
* This avoids fragmentation of the code and allows to keep the logic in one place if the pieces are not reused/reusable, but still allows for save scoping.
*
* As explained by Brian Will:
* https://youtu.be/QM1iUe6IofM?t=2255
*/
function longFunction(): string
{
// 1. do something
$resultOne = (function () {
// this is a safe block of code that can be executed without poluting the outer scope
$localVariable = 'foo';
return 'result1';
})();
// 2. do something else
$resultTwo = (function () use ($resultOne) {
// explicitly only $resultOne is available from the outer scope
$localVariable2 = 'foo2';
return $resultOne.'result2';
})();
// 3. do something that results in two variables
[$resultThree, $resultFour] = (function () use ($resultOne, $resultTwo) {
// do work here by also using $resultOne and $resultTwo from previous steps
return ['three', 'four'];
})();
return $resultTwo . $resultThree . $resultFour;
}
echo longFunction();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment