PHP mistakes to avoid: objects and references

This is a fairly crucial bit of object-oriented PHP, but I only found out about it today after x years, so it’s bound to trip someone else up.

Essentially, if you want to copy some values from an object, doing this is a very bad idea:

$a = new A;
$b = $a;

…because it’s not like copying a variable (passing it by value) where $a and $b are independent, $b is just a pointer to $a. So this:

unset($b->foo);

…will remove foo from $a as well.

Wiser programmers than me may well be saying, “Why do you need to copy an object anyway?”, and indeed I can’t remember doing so before.

I needed it’s properties, so I could write a record of an API call to a logfile (but minus sensitive info like the API keys).  These were indeed removed from the log, unfortunately all the REST calls stopped working and it took a while to realise why.  get_object_vars (which chucks the properties in an array and leaves the original object intact) was what I should have used.

Note objects are passed as pointers, not as references, as explained in great detail here (read the comments.)