$a = '1';
$b = &$a;
$b = "2$b";
Can please anyone helps me, I can not understand what & Operator does when it comes with variables like that, My solution is $a = 1, $b = 21, is that right ?
$a = '1';
$b = &$a;
$b = "2$b";
Can please anyone helps me, I can not understand what & Operator does when it comes with variables like that, My solution is $a = 1, $b = 21, is that right ?
For further actions, you may consider blocking this person and/or reporting abuse
Nacho Colomina Torregrosa -
Andrew Kang-G -
MD ARIFUL HAQUE -
Sohail SJ | chakraframer.com -
Top comments (4)
The & operator in PHP is used for two things in PHP.
One is bitwise AND operator (performs and AND operation between the bits of two variables):
The other use is to indicate a reference to a variable. This is mainly used in functions when you want to allow the function to modify the value passed as a parameter.
This is an example of a regular function:
The output is
Double is 4 - After the call to printDouble, the value of a is 2
.We have passed
number
as value, that is, we pass the function the value of the variable.Now the same example, with just one char change: adding a & to the function parameter.
Now the output is
Double is 4 - After the call to printDouble, the value of a is 4
.What has happended? We have used the & operator on the
number
parameter of the function, and that is called passing the parameter as reference. That is, what the function receives is not the value of the variable, but a reference to it (you may have heard of this in other languages as "pointer").When a variable is passed in a function as reference you can read it, and you will get the value of the referenced variable (2 in the example). But, and here comes the big difference, if you assign a value to the variable you are no longer changing the value of the local parameter, but the value of the variable passed from outside the function.
In the example,
a
contains the value 2, but since in the function the param is doubled, thea
variable is doubled.This behaviour can be useful in some cases, but is also quite dangerous: a function should never alter the data it receives since that may create undesired side effects on the code that calls it. You should be very careful when using it.
As for your example, what you're doing is:
So yes, your solution is right.
Also, for the sake of completeness, this operator should not be confused with the logical AND:
$isCar = $isVehicle && $hasFourWheels;
Thank you and I appreciate your time and effort to help, now everything is clear
ah, yeah?
Is my solution right ?