Skip to content

Commit 5476aef

Browse files
feat: variable scopes
1 parent 796029d commit 5476aef

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed

05_variable_scopes.php

+97
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
<?php
2+
3+
/*
4+
* PHP has three different variable scopes:
5+
* local, global & static
6+
* */
7+
8+
/*
9+
* Local Scope
10+
* A variable declared within a function has a LOCAL SCOPE.
11+
* and can only be accessed within that function.
12+
* */
13+
14+
function showFullName(): string
15+
{
16+
$first_name = 'Hridoy';
17+
$last_name = 'Ahmed';
18+
19+
return $first_name . ' ' . $last_name;
20+
}
21+
22+
$full_name = showFullName();
23+
24+
echo '<pre>';
25+
print_r($full_name);
26+
27+
echo '<pre>';
28+
// print_r($first_name);
29+
// If you comment out the above line will give you a warning.
30+
// Because You Cannot access first_name outside the function as it is a local variable.
31+
32+
33+
/*
34+
* Global Scope
35+
* The global keyword is used to access a global variable from within a function.
36+
* If you update the global variables inside a function it will overwrite the original variable's value.
37+
* PHP also stores all global variables in an array called $GLOBALS[index].
38+
* The index holds the name of the variable.
39+
* This array is also accessible from within functions.
40+
* Can be used to update global variables directly.
41+
* */
42+
43+
$a = 10;
44+
$b = 20;
45+
$c = 30;
46+
47+
function testGlobal(): void
48+
{
49+
global $a, $b, $c;
50+
51+
echo '<p>' . 'Without Updating Global Variable Sum = ' . $a + $b + $c . '</p>';
52+
53+
$a = 100; // Update the global variable
54+
$b = 200;
55+
$c = 300;
56+
57+
echo '<p>' . 'After Updating the values of the global varibles Sum = ' . $a + $b + $c . '</p>';
58+
}
59+
60+
testGlobal();
61+
62+
// Using GLOBALS
63+
$x = 5;
64+
$y = 10;
65+
66+
function testGlobal2(): void
67+
{
68+
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
69+
}
70+
71+
testGlobal2();
72+
echo '<pre>';
73+
echo $y; // outputs 15
74+
75+
/*
76+
* Static Scope
77+
* Normally, when a function is completed/executed, all of its variables are deleted.
78+
* If you update the static variables inside a function it will overwrite the original variable's value.
79+
* If you want a local variable NOT to be deleted, you can use the static keyword.
80+
* Note: The variable is still local to the function.
81+
*/
82+
83+
function testStatic(): void
84+
{
85+
static $x = 0; // Remember the value for the next usage.
86+
echo $x;
87+
$x++;
88+
}
89+
90+
echo '<pre>';
91+
testStatic();
92+
93+
echo '<pre>';
94+
testStatic();
95+
96+
echo '<pre>';
97+
testStatic();

0 commit comments

Comments
 (0)