What is the default scope of a variable declared inside a function in PHP?
Analysis & Theory
Variables declared inside a function are local to that function in PHP.
What keyword is used to access a global variable inside a function?
Analysis & Theory
The `global` keyword is used to access global variables inside a function.
What is the output of this code?
```
<?php
$x = 5;
function test() {
echo $x;
}
test();
?>
```
B
Error or undefined variable
Analysis & Theory
`$x` is a global variable and not accessible directly inside the function without using `global $x;`.
Which superglobal can be used to access a global variable inside a function without using the `global` keyword?
Analysis & Theory
`$GLOBALS['variable_name']` is an associative array of all global variables.
What is the purpose of the `static` keyword in PHP?
A
To make a variable public
B
To store a value globally
C
To preserve a local variable’s value between function calls
Analysis & Theory
The `static` keyword retains a local variable's value between multiple calls to the function.
What will be the output of the following code?
```
<?php
function test() {
static $count = 0;
$count++;
echo $count;
}
test();
test();
test();
?>
```
Analysis & Theory
The `static` variable retains its value across multiple function calls, so the output is `1 2 3`.
If a variable is declared outside all functions, what scope does it have?
Analysis & Theory
A variable declared outside functions has a global scope but isn’t accessible inside functions unless declared with `global` or `$GLOBALS`.
What happens if you try to access a local variable outside its function?
C
It causes an error or undefined variable.
D
It converts to a global variable.
Analysis & Theory
A local variable exists only within the function in which it is declared. Accessing it outside will cause an undefined variable notice.
What is the output of this code?
```
<?php
$x = 10;
function test() {
global $x;
echo $x;
}
test();
?>
```
Analysis & Theory
The `global` keyword makes the global `$x` accessible inside the function, so it outputs `10`.
Which option correctly describes the `static` variable behavior?
A
It is destroyed after the function ends.
B
It retains its value between function calls.
C
It becomes a global variable.
D
It converts to a constant.
Analysis & Theory
`static` variables maintain their value between multiple calls to the function.