尝试通过引用分配来理解运算符优先级

时间:2015-01-11 04:36:58

标签: php reference variable-assignment

Operator precedence表示订单应为:+, &, =。但是此代码执行显示订单为:&, =, +

$b = 1;
$a = & $b + print('print executed');
if ($a == 1)
    echo ' but one was not added and error was not raised';

输出print executed but one was not added and error was not raised

为什么这种情况会改变优先级?

P.S。

$a = new stdClass();

$c = &$a instanceof $a;
var_dump($c); // class stdClass#1 (0) {}

$b = $a instanceof $a;
var_dump($b); // bool(true)

1 个答案:

答案 0 :(得分:2)

可以说,这并没有真正回答你的问题,但考虑一下这个代码:

$b = 1;
$a = &$b + 123;

操作码揭示了以下执行策略:

compiled vars:  !0 = $b, !1 = $a
line     # *  op                       fetch          ext  return  operands
-----------------------------------------------------------------------------
   3     0  >   ASSIGN                                              !0, 1
   4     1      ASSIGN_REF                                   $1      !1, !0
         2      ADD                                          ~2      $1, 123
         3      FREE                                                 ~2

如您所见,通过引用进行分配,并将添加存储在临时变量中,然后释放;基本上,没有操作。

也许文档可能更清晰,但我无法想象这个特定代码有意义的场景:)