Last active
March 11, 2023 18:05
-
-
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…
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 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