0
0
PHPprogramming~10 mins

Global keyword behavior in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Global keyword behavior
Start
Define global variable
Enter function
Use 'global' keyword
Access/modify global variable
Exit function
Global variable updated
End
This flow shows how a global variable is defined outside a function, then accessed and modified inside a function using the 'global' keyword.
Execution Sample
PHP
<?php
$x = 5;
function test() {
  global $x;
  $x = 10;
}
test();
echo $x;
?>
This code defines a global variable $x, modifies it inside a function using 'global', then prints the updated value.
Execution Table
StepActionVariableValueNotes
1Define global variable$x5Global scope
2Call function test()--Enter function scope
3Declare 'global $x' inside function$x5Link local $x to global $x
4Assign $x = 10 inside function$x10Modifies global $x
5Exit function test()--Return to global scope
6Echo $x$x10Prints updated global variable
💡 Function ends and global variable $x is updated to 10
Variable Tracker
VariableStartAfter function callFinal
$x51010
Key Moments - 2 Insights
Why does $x inside the function change the global $x?
Because of the 'global $x;' declaration inside the function (see step 3 in execution_table), the local $x refers to the global $x, so modifying it changes the global variable.
What happens if we don't use 'global' inside the function?
Without 'global', $x inside the function is a new local variable, so changes won't affect the global $x (not shown in table but implied).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of $x after step 4 inside the function?
A10
B5
CUndefined
D0
💡 Hint
Check the 'Value' column at step 4 where $x is assigned 10 inside the function.
At which step does the global variable $x get updated?
AStep 2
BStep 3
CStep 4
DStep 6
💡 Hint
Look at the 'Action' and 'Notes' columns around step 4 where $x is assigned 10.
If we remove 'global $x;' from the function, what would be the output at step 6?
A10
B5
CError
D0
💡 Hint
Without 'global', the function modifies a local $x, so global $x remains unchanged as shown in variable_tracker.
Concept Snapshot
PHP 'global' keyword:
- Declares variables inside functions as global.
- Allows access and modification of global variables.
- Without 'global', variables inside functions are local.
- Changes to global variables persist after function ends.
Full Transcript
This example shows how PHP's 'global' keyword works. We start by defining a global variable $x with value 5. When we enter the function test(), we declare 'global $x;' which links the local $x to the global one. Then we assign 10 to $x inside the function, which updates the global variable. After the function ends, printing $x shows 10, confirming the global variable was changed. Without 'global', the function would only change a local copy, leaving the global $x unchanged.