0
0
PHPprogramming~5 mins

Variable scope in functions in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is variable scope in PHP functions?
Variable scope defines where a variable can be accessed or used in the code. In PHP, variables inside functions are local by default and cannot be accessed outside the function.
Click to reveal answer
beginner
What happens if you try to use a variable declared outside a function inside that function without any special keyword?
The function will not see the outside variable because variables inside functions are local by default. You need to use the global keyword or pass the variable as a parameter to access it.
Click to reveal answer
beginner
How do you access a global variable inside a PHP function?
Use the global keyword inside the function before the variable name. This tells PHP to use the variable from the global scope.
Click to reveal answer
intermediate
What is the static keyword used for in PHP functions?
The static keyword keeps a local variable's value between function calls. It means the variable does not reset each time the function runs.
Click to reveal answer
beginner
Explain the difference between local and global variables in PHP.
Local variables exist only inside the function where they are declared. Global variables exist outside functions and can be accessed anywhere if declared global inside functions.
Click to reveal answer
What keyword allows a function to access a variable declared outside it?
Aglobal
Blocal
Cstatic
Dpublic
What is the scope of a variable declared inside a function without any keyword?
AGlobal
BPublic
CStatic
DLocal
Which keyword keeps a variable's value between function calls?
Aglobal
Blocal
Cstatic
Dconst
If you want to use a global variable inside a function without global, what is a good alternative?
APass it as a function parameter
BDeclare it again inside the function
CUse <code>static</code> keyword
DUse <code>const</code> keyword
What happens if you try to access a local variable outside its function?
AIt works fine
BIt causes an error or undefined variable
CIt accesses the global variable
DIt converts to static
Explain how variable scope works inside PHP functions and how to access variables from outside the function.
Think about where variables live and how to share them with functions.
You got /4 concepts.
    Describe the purpose of the static keyword in PHP functions and give an example of when it might be useful.
    Consider a counter that remembers its value each time a function runs.
    You got /4 concepts.