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