Recall & Review
beginner
What does the
global keyword do in PHP?It allows a function to access variables defined outside its scope, specifically global variables, by linking the local variable to the global one.
Click to reveal answer
intermediate
How do you access a global variable inside a function without using the
global keyword?You can access global variables using the
$GLOBALS array, for example: $GLOBALS['varName'].Click to reveal answer
beginner
What happens if you modify a global variable inside a function without declaring it
global?The function creates a new local variable with the same name, leaving the global variable unchanged.
Click to reveal answer
beginner
Example: What will this code output?<br><pre> $x = 5;<br>function test() {<br> global $x;<br> $x = 10;<br>}<br>test();<br>echo $x;</pre>It will output
10 because the global keyword links the local $x to the global $x, so the change affects the global variable.Click to reveal answer
intermediate
Why is using the
global keyword sometimes discouraged?Because it can make code harder to understand and debug by creating hidden dependencies between functions and global state. It's often better to pass variables as parameters.
Click to reveal answer
What does the
global keyword do inside a PHP function?✗ Incorrect
The
global keyword links the local variable to the global variable with the same name.How can you access a global variable inside a function without using
global?✗ Incorrect
The
$GLOBALS array holds all global variables and can be used inside functions.What will happen if you assign a value to a global variable inside a function without declaring it
global?✗ Incorrect
Without
global, the assignment creates a new local variable.Which of these is a downside of using the
global keyword?✗ Incorrect
Using
global can hide dependencies and make code harder to maintain.Given
$a = 3; outside a function, what will echo $a; output after this function?<br>function change() { global $a; $a = 7; } change();✗ Incorrect
The
global keyword links the function's $a to the global $a, so the value changes to 7.Explain how the
global keyword works in PHP functions and why it is used.Think about variable scope and how functions normally can't see outside variables.
You got /4 concepts.
Describe the alternatives to using the
global keyword for accessing global variables inside functions.Consider safer ways to share data between functions.
You got /4 concepts.