How can you pass a variable by reference?
How can you pass a variable by reference?
Here's how you can pass a variable by reference in PHP:
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:
function incrementByReference(&$num) {
$num++;
}
$x = 5;
echo "Before incrementing: $x\n";
incrementByReference($x);
echo "After incrementing: $x\n";
Output:
Before incrementing: 5
After incrementing: 6
In this example:
The incrementByReference
function takes a parameter $num
and prepends it with an ampersand (&
), indicating that it expects a reference to a variable.
Inside the function, when you modify the value of $num
, it directly affects the original variable passed to the function.
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.
After the function call, the value of $x
is incremented by 1 because the function modified the original variable.
You can also pass arrays by reference to a functio...
entry
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào