Complete the code to create a closure that returns a greeting.
<?php
$greet = function($name) {
return "Hello, " . [1] . "!";
};
echo $greet('Alice');
?>The closure uses the parameter $name to build the greeting string.
Complete the code to use the 'use' keyword to access an external variable inside a closure.
<?php $message = 'Hello'; $greet = [1]($name) use ($message) { return $message . ', ' . $name . '!'; }; echo $greet('Bob'); ?>
The closure is defined with the function keyword and uses use to access $message from outside.
Fix the error in the closure to correctly modify the external variable by reference.
<?php $count = 0; $increment = function() use (&[1]) { [1]++; }; $increment(); echo $count; ?>
The variable $count is passed by reference using &$count so the closure can modify it.
Fill both blanks to create a closure that filters an array using an external threshold variable.
<?php $threshold = 10; $numbers = [5, 12, 8, 20]; $filtered = array_filter($numbers, function($num) use ([1]) { return $num [2] $threshold; }); print_r($filtered); ?>
The closure uses use ($threshold) to access the external variable and filters numbers greater than the threshold.
Fill all three blanks to create a closure that returns a multiplier function with a captured factor.
<?php
function multiplier($factor) {
return function($number) use ([1]) {
return $number [2] [3];
};
}
$double = multiplier(2);
echo $double(5);
?>The closure captures $factor and multiplies the input number by it.