Câu hỏi phỏng vấn PHP
Câu hỏi

What are the different scopes of variables?

Câu trả lời

Here is an explanation of the different scopes of variables in PHP:

Variable Scopes in PHP

In PHP, variables can have different scopes depending on where they are defined and used. The main variable scopes are:

  1. Local Scope
  2. Global Scope
  3. Static Scope
  4. Parameter Scope

Let's discuss each scope in detail:

1. Local Scope

  • Variables declared within a function have a local scope and can only be accessed within that function.
  • Local variables are created when the function is called and destroyed when the function completes execution.
  • You cannot access a local variable from outside the function.

Example:

php Copy
function myFunction() {
    $x = 5; // $x has local scope
    echo "Value of x inside the function: $x";
}

myFunction(); // Calls the function
echo "Value of x outside the function: $x"; // Error: $x is not defined

2. Global Scope

  • Variables declared outside of all functions and classes have a global scope.
  • Global variables can be accessed throughout the entire script, including inside functions.
  • To access a global variable inside a function, you need to use the global keyword or the $GLOBALS superglobal array.

Example:

php Copy
$x = 5; // $x has global scope

function myFunction() {
    global $x;
    echo ...
junior

junior

Gợi ý câu hỏi phỏng vấn

senior

Compare MySQLi or PDO - what are the pros and cons?

senior

What's better at freeing memory with PHP: unset() or $var = null ?

junior

What is the difference between var_dump() and print_r() ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào