Scopes (space of visibility)
The scoping rules are those used in most high-level programming languages.
They are not those of PHP.
They are four level of scopes:
- the global one,
- the one of a class,
- the body of a function,
- and the body of a control structure or block.
Variables declared inside a scope are visible in any inner scope. They can't
be redeclared inside an inner scope.
Variables declared in the global level are usable inside functions, and inside
body of control structures. Not inside a class.
This is the same for variables declared in the body of a class, and each class
is equivalent to a separate global level.
Variables declared in the body of a function are usable inside the body of
a control structure, and a variable that is declared or visible inside the
body of a control structure is visible inside embedded control structures.
You can't redeclare a variable where it remains visible. You can only redeclare
it when its scope is closed, in successive functions of successive control
structures.
Headers of control structures
The header of a function has the scope of the function.
Headers of control structures are considered as visible in the scope of the
structure, and variables declared here are destroyed at end of the block.
Examples on structure header and scope. | for
int i in 1..3 print i /for print i ` error, i doen't exists outside for block. |
Displays: | > Error, "i" undeclared |
"let" statement
The scope of the let statement that ends a while control structure is a part of the body of the while structure.
Scope and PHP
In PHP, a variable assigned or used inside a function is considered to be
internal to the function, even if it has been declared as global, but if it
is explicitely declared "global".
Since the rules of Scriptol and PHP are different, the "global" operator has
to be added to variables of the target code in most case, but this is entirely
managed by the compiler and you don't have to deal with that, but if you use
external PHP variables. In this case, they have to be imported for the compiler
processes them correctly. (see import).
More on scopes in the chapter about classes.