Junior — Middle
Can you list the different types of variable scopes in programming?
sobes.tech AI
Answer from AI
In programming, the scope of variables defines where exactly in the code the variable is accessible.
Main types of scopes:
- Global scope — the variable is accessible throughout the entire program code.
- Local scope — the variable is only visible inside the function or block where it is declared.
- Class scope (for OOP) — class member variables are accessible within class methods.
- Static scope — variables that retain their value between function calls.
In PHP, for example:
$globalVar = 'global'; // global variable
function test() {
$localVar = 'local'; // local variable
global $globalVar; // access to global variable inside the function
echo $globalVar; // outputs 'global'
}
class MyClass {
public $property = 'class property';
function show() {
echo $this->property; // access to class property
}
}
Understanding scopes is important for managing variable visibility and lifetime.