0
0
PHPprogramming~10 mins

Why global state is dangerous 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 declare a global variable in PHP.

PHP
<?php
$counter = 0;
function increment() {
    global [1];
    $counter++;
}
?>
Drag options to blanks, or click blank then click option'
A$counter
B$count
C$globalCounter
D$var
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to use the global keyword.
Using a different variable name inside the function.
2fill in blank
medium

Complete the code to modify a global variable inside a function.

PHP
<?php
$score = 10;
function addPoints() {
    global [1];
    $score += 5;
}
?>
Drag options to blanks, or click blank then click option'
A$points
B$total
C$score
D$value
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name inside the function.
Not declaring the variable as global.
3fill in blank
hard

Fix the error in the code to correctly access the global variable inside the function.

PHP
<?php
$count = 5;
function showCount() {
    echo [1];
}
showCount();
?>
Drag options to blanks, or click blank then click option'
A$count
Bglobal $count
Cglobal $GLOBALS['count']
D$GLOBALS['count']
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to echo the variable without declaring it global.
Using 'global $count' inside echo statement.
4fill in blank
hard

Fill both blanks to create a function that modifies a global variable safely.

PHP
<?php
$visits = 0;
function visitPage() {
    [1] $visits;
    $visits [2] 1;
}
?>
Drag options to blanks, or click blank then click option'
Aglobal
B+=
C-=
D*=
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to declare the variable as global.
Using the wrong operator to increment.
5fill in blank
hard

Fill all three blanks to demonstrate why global state can cause bugs in PHP.

PHP
<?php
$flag = false;
function toggleFlag() {
    [1] $flag;
    if ($flag [2] false) {
        $flag [3] true;
    } else {
        $flag = false;
    }
}
?>
Drag options to blanks, or click blank then click option'
Aglobal
B==
C=
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using assignment operator instead of comparison in the if condition.
Not declaring the variable as global.