Junior — Middle
Milline on ampersandi roll programmeerimises ja kuidas see erineb teistest operaatoritest?
sobes.tech AI
Vastus AI-lt
In PHP, the ampersand (&) is used for working with references and bitwise operations. The main roles of &:
- Passing by reference: allows a function to directly modify the passed variable, rather than its copy.
function addOne(&$num) {
$num += 1;
}
$a = 5;
addOne($a);
echo $a; // Will output 6
- Creating references: you can create a reference to a variable, so that two variables point to the same value.
$b = 10;
$c = &$b;
$c = 15;
echo $b; // Will output 15
- Bitwise AND operator: in expressions with numbers, & is used as a bitwise "AND" operator.
$x = 6; // binary 110
$y = 3; // binary 011
$z = $x & $y; // binary 010, which is 2
The difference from other operators is that & can function as a reference operator (changing the behavior of data transmission), as well as a bitwise operator, while other operators usually perform arithmetic or logical operations without affecting references.