Php By Reference

前端 未结 5 940
夕颜
夕颜 2020-12-17 06:03

Can someone please explain what the \"&\" does in the following:

class TEST {

}

$abc =& new TEST();

I know it is by reference. Bu

5条回答
  •  孤城傲影
    2020-12-17 07:04

    It might be helpful to think of it like this: In PHP, all variables are really some sort of pointer: The entries in the symbol table - the thing which maps variable names to values - contain a zval * in the C implementation of the Zend Engine.

    During assignment - this includes setting function arguments - magic will happen:

    If you do $a = $b, a copy of the value pointed to by the symbol table entry of $b will be created and a pointer to this new value will be placed in the symbol table entry for $a. Now, $a and $b will point to different values. PHP uses this as its default calling convention.

    If you do $a =& $b, the symbol table entry for $a will be set to the pointer contained in the symbol table entry for $b. This means $a and $b now point to the same value - they are aliases of each other with equal rights until they are rebound by the programmer. Also note that $a is not really a reference to $b - they are both pointers to the same object.

    That's why calling them 'aliases' might be a good idea to emphasize the differences to C++' reference implementation:

    In C++, a variable containing a value and a reference created from this variable are not equal - that's the reason why there are things like dangling references.

    To be clear: There is no thing like a reference type in PHP, as all variables are already internally implemented as pointers and therefore every one of them can act as a reference.

    PHP5 objects are still consistent with this description - they are not passed by reference, but a pointer to the object (the manual calls it an 'object identifier' - it might not be implemented as an actual C pointer - I did not check this) is passed by value (meaning copied on assignment as described above).

    Check the manual for details on the relation between PHP5 objects and references.

提交回复
热议问题