0
0
PHPprogramming~10 mins

Closures and variable binding with use in PHP - Interactive Code Practice

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 uses the variable $x.

PHP
<?php
$x = 5;
$func = function() use ([1]) {
    return $x * 2;
};
echo $func();
?>
Drag options to blanks, or click blank then click option'
A$x
B$y
C$z
D$a
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name not defined outside the closure.
Forgetting to use the use keyword.
2fill in blank
medium

Complete the code to modify the external variable $count inside the closure.

PHP
<?php
$count = 0;
$increment = function() use (&[1]) {
    $count++;
};
$increment();
echo $count;
?>
Drag options to blanks, or click blank then click option'
A$value
B$count
C$num
D$total
Attempts:
3 left
💡 Hint
Common Mistakes
Not using & to pass by reference.
Using a different variable name inside use.
3fill in blank
hard

Fix the error in the closure by correctly importing the variable $name.

PHP
<?php
$name = "Alice";
$greet = function() use ([1]) {
    return "Hello, " . $name;
};
echo $greet();
?>
Drag options to blanks, or click blank then click option'
A$this->name
B$_name
C$name
D$greet
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to access external variables directly inside the closure.
Using incorrect variable names.
4fill in blank
hard

Fill both blanks to create a closure that captures $a and $b by value and returns their sum.

PHP
<?php
$a = 3;
$b = 4;
$sum = function() use ([1], [2]) {
    return [1] + [2];
};
echo $sum();
?>
Drag options to blanks, or click blank then click option'
A$a
B$b
C$c
D$d
Attempts:
3 left
💡 Hint
Common Mistakes
Using variables not defined outside the closure.
Not importing variables with use.
5fill in blank
hard

Fill all three blanks to create a closure that captures $x by reference, increments it, and returns the new value.

PHP
<?php
$x = 10;
$increment = function() use ([1]) {
    [2]++;
    return [3];
};
echo $increment();
?>
Drag options to blanks, or click blank then click option'
A&$x
B$x
D$y
Attempts:
3 left
💡 Hint
Common Mistakes
Not using reference in use.
Using different variable names inside the closure.