当你通过引用传递一个对象时,会发生什么?

a question for anyone who knows. The PHP documentation (for php5) clearly states that you don't pass objects by references in php, because for a method that accepts an object, the value actually being passed is an "object identifier which allows object accessors to find the actual object". The question is, what is happening when you actually do do this?

Consider the following code:

<?php
function foo(&$arg){
    if(is_array($arg)){
         print $arg['foo'];
    }
    if(is_object($arg)){
        print $arg->{'foo'};
    }
}
$o1 = new \stdClass;
$o1->foo = 'bar';
$a1 = ['foo'=>'bar'];
print sprintf("O1 foo: %s", foo($o1));
print sprintf("a1 foo: %s", foo($a1));

This correctly outputs:

o1 foo: bar
a1 foo: bar

The question is why? Can anyone describe what's happening with this object identifier reference that still allows accessing the actual object?

Any variable that holds an object is not holding the object directly. It holds an identifier of the object. Imagine it as the object living somewhere in an object pool having a number attached to it, e.g. #5. All the variable contains is "object #5". PHP knows that the variable refers to an object and that it's supposed to be object #5.

Whenever you work with such a variable holding an object reference, PHP looks up the referenced object from the object pool.

When you pass such a variable into a function, PHP makes a copy of that reference. There are then two variables holding the content "object #5". Not the object itself has been copied, just this tiny note which says "object #5".

When you pass such a variable into a function by reference, well, you're passing that note "object #5" by reference. PHP won't make a copy of it. But it's still just a variable saying "object #5", so when you're trying to work with it, PHP will look up the object from the pool.

This object reference mechanism is not the same as the & pass-by-reference mechanism. The object reference mechanism works exactly the same as all other pass-by-value operations; it's just that a value which represents a reference to an object is always being treated in a specific way (PHP has to look up the actual object elsewhere).