Back to questions
JuniorTheoryCommon
What does the program print?
<?php
function applyTwice(callable $f, int $x): int
{
return $f($f($x));
}
$inc = function (int $n): int {
return $n + 3;
};
echo applyTwice($inc, 1), ' ', applyTwice('abs', -5), "\n";7 5
- Expecting
4, as if$fran once:$f($f($x))calls the function on$x, then again on that result, so$incadds3twice. - Expecting a
TypeErrorfor'abs': a string that holds the name of a function is a validcallable, and calling it runs that function.
- How would you write
applyTwiceso that it applies$fa given number of times? - Which values can a
callableparameter accept besides an anonymous function?