Nested Objects, Arrays, and Variable Variables in PHP

PHP Class and Arrays

(Standard) objects and arrays in PHP are typically dynamic. We can create and change them as we go, we are able to convert one to another, and perform all sorts of magic on them at runtime. Lovely. There are some downsides like memory usage, but most of us accept these few annoyances or find a way to work around them.

One of the operations PHP is less suited for, is accessing data halfway an object or array using a variable variable. Normal variable names are no problem, but if you try to access variables by using a variable variable like this:

Well, a lot of people get stuck trying to figure this out. There are enough solutions, but one more can’t hurt.

The following code is a short class with static members to get a reference, get a value, or set a value of a nested variable.

This is an example of how to use it:

Above will be sufficient for most situations. If this doesn’t work for you, be sure to check the following:

  • Could the variable you are referring to, in fact be a string offset or an overloaded object? This would normally present itself with the error message “PHP Fatal error:  Cannot create references to/from string offsets nor overloaded objects in …”.
  • Does an access modifier of the targeted attribute (or one of the a parent attributes) prevent access? This would be recognizable by an error message like “PHP Fatal error:  Cannot access private property …”.
  • Is the targeted variable within scope? The default behaviour is to create a new variable within the current scope.

Small same-day-update: Flaheadle made me aware of an old school coding habit of mine. I was using “call-time pass-by-reference”, which is deprecated. The code above is fixed.