0
0
PHPprogramming~10 mins

Variable scope in functions 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 print the global variable inside the function.

PHP
<?php
$number = 10;
function showNumber() {
    global [1];
    echo $number;
}
showNumber();
?>
Drag options to blanks, or click blank then click option'
Anumber
B$number
C$this
Dvar
Attempts:
3 left
💡 Hint
Common Mistakes
Including the $ sign when declaring a global variable inside a function.
Using a different variable name inside the function.
2fill in blank
medium

Complete the code to return the value of the global variable inside the function.

PHP
<?php
$value = 5;
function getValue() {
    global [1];
    return $value;
}
echo getValue();
?>
Drag options to blanks, or click blank then click option'
Avalue
Bthis
C$value
Dvar
Attempts:
3 left
💡 Hint
Common Mistakes
Using $value with global keyword.
Trying to access the variable without declaring it global.
3fill in blank
hard

Fix the error in the function to correctly modify the global variable.

PHP
<?php
$count = 0;
function increment() {
    [1] $count;
    $count++;
}
increment();
echo $count;
?>
Drag options to blanks, or click blank then click option'
Alocal
Bglobal
Cstatic
Dpublic
Attempts:
3 left
💡 Hint
Common Mistakes
Using local or static instead of global.
Not declaring the variable as global and trying to modify it.
4fill in blank
hard

Fill both blanks to create a function that uses a static variable to count calls.

PHP
<?php
function counter() {
    static [1] = 0;
    [2]++;
    return $count;
}
echo counter();
echo counter();
?>
Drag options to blanks, or click blank then click option'
A$count
B$counter
D$calls
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for declaration and increment.
Not using the static keyword.
5fill in blank
hard

Fill all three blanks to create a function that accesses a global variable and modifies it.

PHP
<?php
$score = 10;
function updateScore() {
    [1] [2];
    $score [3] 5;
}
updateScore();
echo $score;
?>
Drag options to blanks, or click blank then click option'
Aglobal
Bscore
C+=
D-=
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to declare the variable as global.
Using the wrong operator like -= instead of +=.