As we know, functions and classes change the scope of the current variable. If, while, and other branch loop structures inherit the external scope, that is, the external variables are visible inside the branch loop structure.
However, the C language does not support the internal scopes of if, while and other branch loop structures, whereas PHP does not.
In PHP, if, while, and other local variables declared in the branch loop structure are still valid after the branch loop structure.
For example, variables declared in a function are invisible outside the function.
C language: 01 # include <stdio. h>
02
03 int Foo ()
04 {
05 int bar;
06 bar = 3;
07}
08
09 int main ()
10 {
11 printf ("% d \ n", bar );
12 Return 0;
13}
Error:
Scope. C: In function 'main ':
Scope. C: 11: Error: 'bar' is not declared (used for the first time in this function)
Scope. C: 11: Error: (even if it appears multiple times in a function, each undeclared identifier
Scope. C: 11: Error: only one report is reported in the function .)
PHP language: 1 <? PHP
2 function Foo ()
3 {
4 $ bar = 1;
5}
6
7 Echo $ bar;
Error:
Notice: undefined variable: bar in scope. php on line 7
PHP notice: undefined variable: bar in scope. php on line 7
The if, while, and other loop branch structures inherit the external scope, that is, the external variables are visible inside the loop branch structure.
Similar:
C language: 01 # include <stdio. h>
02
03 int main ()
04 {
05 int Foo = 1;
06 if (1)
07 {
08 int bar = Foo;
09 printf ("% d \ n", bar );
10}
11
12 while (1)
13 {
14 int bar = Foo;
15 printf ("% d \ n", bar );
16 break;
17}
18
19 Return 0;
20}
Output:
1
1
PHP language: 01 <? PHP
02 $ Foo = 1;
03 if (1)
04 {
05 $ bar = $ Foo;
06 echo $ bar, "\ n ";
07}
08
09 while (1)
10 {
11 $ bar = $ Foo;
12 echo $ bar, "\ n ";
13 break;
14}
Output:
1
1
But it's different.
C language: 01 # include <stdio. h>
02
03 int main ()
04 {
05 int Foo = 1;
06 if (1)
07 {
08 int bar = Foo;
09 printf ("% d \ n", bar );
10}
11
12 printf ("% d \ n", bar );
13
14 While (1)
15 {
16 int bar = Foo;
17 printf ("% d \ n", bar );
18 break;
19}
20
21 printf ("% d \ n", bar );
22
23 return 0;
24}
Error:
Scope. C: In function 'main ':
Scope. C: 12: Error: 'bar' is not declared (used for the first time in this function)
Scope. C: 12: Error: (even if it appears multiple times in a function, each undeclared identifier
Scope. C: 12: Error: only one report is reported in the function .)
PHP language
01 <? PHP
02 $ Foo = 1;
03 if (1)
04 {
05 $ bar = $ Foo;
06 echo $ bar ++, "\ n ";
07}
08
09 echo $ bar, "\ n ";
10
11 while (1)
12 {
13 $ bar2 = $ Foo;
14 echo $ bar2 ++, "\ n ";
15 break;
16}
17
18 echo $ bar2, "\ n ";
Output:
1
2
1
2
This is what you need to pay attention!