The idea that the code flow is now no longer linear, and that the programmer now has to understand perfectly the odd rules by which the execution of code now just jumps around… boggles the mind.
A closure-based approach would have been much more semantically sane; if a little syntactically ugly. But then again, how hard would it have been to add a nicer closure syntax to PHP, instead of creating this mess of a feature?
Take this:
def each_line_in_file
f = File.open('hello.txt', 'r')
while line = f.gets
yield line
end
f.close
end
each_line_in_file do |l|
puts l
end
This is a real-world Ruby example of the feature. The semantics here are clear, each_line is a higher-order function which takes a closure as an arguments, and calls it (yields to it) for each line in the file. Ruby allows the programmer to use the yield keyword to avoid having to declare the closure as an argument (`def each_line(&block)`).The same can even be implemented in PHP as it stands today, although the syntax is quite unsightly:
function each_line_in_file($callback) {
$f = fopen('hello.txt', 'r');
while (null !== ($line = fgets($f))) {
$callback($line);
}
fclose(f);
}
each_line_in_file(function ($l) {
echo $l."\n";
});