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

How can you pass a variable by reference?

Câu trả lời

Here's how you can pass a variable by reference in PHP:

Passing Variables by Reference

To pass a variable by reference in PHP, you need to use the ampersand (&) symbol before the variable name in both the function definition and the function call. Here's an example:

php Copy
function incrementByReference(&$num) {
    $num++;
}

$x = 5;
echo "Before incrementing: $x\n";

incrementByReference($x);
echo "After incrementing: $x\n";

Output:

Copy
Before incrementing: 5
After incrementing: 6

In this example:

  1. The incrementByReference function takes a parameter $num and prepends it with an ampersand (&), indicating that it expects a reference to a variable.

  2. Inside the function, when you modify the value of $num, it directly affects the original variable passed to the function.

  3. In the function call, we pass the variable $x without the ampersand, but PHP automatically creates a reference to $x because the function expects a reference.

  4. After the function call, the value of $x is incremented by 1 because the function modified the original variable.

Passing Arrays by Reference

You can also pass arrays by reference to a functio...

entry

entry

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

senior

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

middle

What exactly is the the difference between array_map , array_walk and array_filter ?

senior

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

Bình luận

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

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