I've encountered this code, but I can't understand its logic. Could someone explain why the output is the way it is?
<?php
$functions = [
function($next) {
echo 'A' .PHP_EOL;
$next();
},
function($next) {
echo 'B' .PHP_EOL;
$next();
},
function($next) {
echo 'C' .PHP_EOL;
$next();
}
];
$a = function() {
echo 'Main Content' .PHP_EOL;
};
foreach($functions as $function) {
$a = fn() => $function($a);
}
$a();
Output:
C B A Main Content
It's a kind of reversed invocation, the code snippet is setting an initial callback function
line 18and then looping over the$functionsarray, overriding the old variable$aby the new function in the loop. At the end, the last function (the one withecho 'C' .PHP_EOL;) is being called, causing an initial call to the$next()callbackline 14, which is - from the foreach loop - points to thebfunction, which is being called, causing the invocation of the$next()callbackline 10and so on. Until it reaches the initial function declaration.