0
0
PHPprogramming~5 mins

Global keyword behavior in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ALinks a local variable to a global variable of the same name
BCreates a new local variable
CDeletes a global variable
DMakes a variable private
How can you access a global variable inside a function without using global?
AUsing <code>const</code> keyword
BUsing <code>static</code> keyword
CUsing the <code>$GLOBALS</code> array
DYou cannot access it
What will happen if you assign a value to a global variable inside a function without declaring it global?
AThe global variable changes
BThe variable becomes constant
CAn error occurs
DA new local variable is created
Which of these is a downside of using the global keyword?
AIt creates hidden dependencies and can make debugging harder
BIt improves performance
CIt makes code easier to read
DIt automatically documents code
Given $a = 3; outside a function, what will echo $a; output after this function?<br>
function change() { global $a; $a = 7; } change();
A3
B7
CError
DNothing
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.