<?php
$b="c";
$c=7;
$i=&$c+$$b;
var_dump($i);
?>
Why my output is int(7)?Can you tell me the reason?I think $i value is 7+7=14 but the result let me fuzzy.
<?php
$b="c";
$c=7;
$i=&$c+$$b;
var_dump($i);
?>
Why my output is int(7)?Can you tell me the reason?I think $i value is 7+7=14 but the result let me fuzzy.
It is because of reference. Precedence Reference + string = Reference. Consider this.
$b = 7;
$a = &$b; // $a now points to $b;
$a = '?'; // The value where $a points is '?'
echo $b; // 7
Now $a is pointer, a reference to $b; You can not add string on that.
The precedence of & is being preferred over +.
Check this for more detail
EDIT
One interesting test for better understanding.
$a = 7;
$d = ($c = &$a + 1); // It is composite expression;
echo $c; // again 7 because & is given preference to +
echo $d; // 8 because that is the output of internal expression.
To be very frank, this is weirdly new to me.
Replace
$i=&$c+$$b;
with
echo &$c+$$b;
and you get a syntax error. Doing
$d=3;
$i=&$c+$d;
you get also 7
, but doing $i = $d+&$c;
yields a syntax error. In your example, doing, then, $i++;
increments both $i
and $c
.
The PHP parser expects VAR = REFERENCE;
and stops after it gets the reference (i.e. it ignores $$b
). Anyway doing REF + integer
has a meaning in C derived languages, but not in PHP.
Note that &
is not only the 'reference' operator, it's also the bitwise (AND) operator. The unary version is for references, the binary one is for bitwise. The language grammar is more complex for &
, that could explain the problem.
That's a PHP bug. The parser should also yield an error in the example you give. Don't use that anyway as it has no meaning and will be likely / hopefully rejected in future releases.