0
0
PHPprogramming~10 mins

Why closures matter in PHP - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a closure that returns a greeting.

PHP
<?php
$greet = function($name) {
    return "Hello, " . [1] . "!";
};
echo $greet('Alice');
?>
Drag options to blanks, or click blank then click option'
Aname
Bname()
C$this
D$name
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the $ sign before the variable name.
Using a variable name not defined in the function parameters.
2fill in blank
medium

Complete the code to use the 'use' keyword to access an external variable inside a closure.

PHP
<?php
$message = 'Hello';
$greet = [1]($name) use ($message) {
    return $message . ', ' . $name . '!';
};
echo $greet('Bob');
?>
Drag options to blanks, or click blank then click option'
Afn
Bclosure
Cfunction
Dcallable
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'fn' instead of 'function' when 'use' is needed.
Not including the 'use' keyword to access external variables.
3fill in blank
hard

Fix the error in the closure to correctly modify the external variable by reference.

PHP
<?php
$count = 0;
$increment = function() use (&[1]) {
    [1]++;
};
$increment();
echo $count;
?>
Drag options to blanks, or click blank then click option'
Acount
Bincrement
Ccounter
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name inside the closure.
Not passing the variable by reference with &.
4fill in blank
hard

Fill both blanks to create a closure that filters an array using an external threshold variable.

PHP
<?php
$threshold = 10;
$numbers = [5, 12, 8, 20];
$filtered = array_filter($numbers, function($num) use ([1]) {
    return $num [2] $threshold;
});
print_r($filtered);
?>
Drag options to blanks, or click blank then click option'
A$threshold
B>
C<
D$num
Attempts:
3 left
💡 Hint
Common Mistakes
Not using the 'use' keyword to access the external variable.
Using the wrong comparison operator.
5fill in blank
hard

Fill all three blanks to create a closure that returns a multiplier function with a captured factor.

PHP
<?php
function multiplier($factor) {
    return function($number) use ([1]) {
        return $number [2] [3];
    };
}
$double = multiplier(2);
echo $double(5);
?>
Drag options to blanks, or click blank then click option'
A$factor
B*
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Not capturing the variable with 'use'.
Using the wrong operator for multiplication.