DEV Community

Discussion on: Are PHP objects passed by reference ?

Collapse
 
dakujem profile image
Andrej Rypo

It is called an "object handle", technically. One can inspect the handle of an object by calling spl_object_id.

The handle is a form of a pointer. Different from those in C, where pointers are memory addresses. In PHP they are implemented as "counted references".

"Objects are passed by reference by default" is a simplification hiding the actual implementation complexities. The "object handles" are very similar in behaviour to regular references to values. Read more in Objects and references.

Collapse
 
nicolus profile image
Nicolus

Thanks, I didn't know about spl_object_id() (it's actually more straightforward than using var_dump() as I suggested), I added it below the var_dump example.

The "Objects and references" page from the doc is what prompted me to write this article because I found it a little obtuse for a junior dev, and it didn't provide examples of situations where the "objects are passed by reference" simplification doesn't cut it.

And thanks for the "counted references" article, I just fell into a new rabbit hole :-p

Collapse
 
dakujem profile image
Andrej Rypo

It's a bit complex, but simply by understanding the concept of counted references, one can get a hint on how garbage collectors work and also understand the meaning behind WeakMap and WeakReference.
The concept is also used in ther languages that use garbage collection.